babylon.max.js 4.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525
  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. /**
  1369. * Ray from a pointer if availible (eg. 6dof controller)
  1370. */
  1371. _this.ray = null;
  1372. _this.skipOnPointerObservable = false;
  1373. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1374. return _this;
  1375. }
  1376. return PointerInfoPre;
  1377. }(PointerInfoBase));
  1378. BABYLON.PointerInfoPre = PointerInfoPre;
  1379. /**
  1380. * This type contains all the data related to a pointer event in Babylon.js.
  1381. * 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.
  1382. */
  1383. var PointerInfo = /** @class */ (function (_super) {
  1384. __extends(PointerInfo, _super);
  1385. function PointerInfo(type, event, pickInfo) {
  1386. var _this = _super.call(this, type, event) || this;
  1387. _this.pickInfo = pickInfo;
  1388. return _this;
  1389. }
  1390. return PointerInfo;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfo = PointerInfo;
  1393. })(BABYLON || (BABYLON = {}));
  1394. //# sourceMappingURL=babylon.pointerEvents.js.map
  1395. var BABYLON;
  1396. (function (BABYLON) {
  1397. BABYLON.ToGammaSpace = 1 / 2.2;
  1398. BABYLON.ToLinearSpace = 2.2;
  1399. BABYLON.Epsilon = 0.001;
  1400. /**
  1401. * Class used to hold a RBG color
  1402. */
  1403. var Color3 = /** @class */ (function () {
  1404. /**
  1405. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1406. * @param r defines the red component (between 0 and 1, default is 0)
  1407. * @param g defines the green component (between 0 and 1, default is 0)
  1408. * @param b defines the blue component (between 0 and 1, default is 0)
  1409. */
  1410. function Color3(
  1411. /**
  1412. * Defines the red component (between 0 and 1, default is 0)
  1413. */
  1414. r,
  1415. /**
  1416. * Defines the green component (between 0 and 1, default is 0)
  1417. */
  1418. g,
  1419. /**
  1420. * Defines the blue component (between 0 and 1, default is 0)
  1421. */
  1422. b) {
  1423. if (r === void 0) { r = 0; }
  1424. if (g === void 0) { g = 0; }
  1425. if (b === void 0) { b = 0; }
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. }
  1430. /**
  1431. * Creates a string with the Color3 current values
  1432. * @returns the string representation of the Color3 object
  1433. */
  1434. Color3.prototype.toString = function () {
  1435. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1436. };
  1437. /**
  1438. * Returns the string "Color3"
  1439. * @returns "Color3"
  1440. */
  1441. Color3.prototype.getClassName = function () {
  1442. return "Color3";
  1443. };
  1444. /**
  1445. * Compute the Color3 hash code
  1446. * @returns an unique number that can be used to hash Color3 objects
  1447. */
  1448. Color3.prototype.getHashCode = function () {
  1449. var hash = this.r || 0;
  1450. hash = (hash * 397) ^ (this.g || 0);
  1451. hash = (hash * 397) ^ (this.b || 0);
  1452. return hash;
  1453. };
  1454. // Operators
  1455. /**
  1456. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1457. * @param array defines the array where to store the r,g,b components
  1458. * @param index defines an optional index in the target array to define where to start storing values
  1459. * @returns the current Color3 object
  1460. */
  1461. Color3.prototype.toArray = function (array, index) {
  1462. if (index === undefined) {
  1463. index = 0;
  1464. }
  1465. array[index] = this.r;
  1466. array[index + 1] = this.g;
  1467. array[index + 2] = this.b;
  1468. return this;
  1469. };
  1470. /**
  1471. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1472. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1473. * @returns a new {BABYLON.Color4} object
  1474. */
  1475. Color3.prototype.toColor4 = function (alpha) {
  1476. if (alpha === void 0) { alpha = 1; }
  1477. return new Color4(this.r, this.g, this.b, alpha);
  1478. };
  1479. /**
  1480. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1481. * @returns the new array
  1482. */
  1483. Color3.prototype.asArray = function () {
  1484. var result = new Array();
  1485. this.toArray(result, 0);
  1486. return result;
  1487. };
  1488. /**
  1489. * Returns the luminance value
  1490. * @returns a float value
  1491. */
  1492. Color3.prototype.toLuminance = function () {
  1493. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1494. };
  1495. /**
  1496. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1497. * @param otherColor defines the second operand
  1498. * @returns the new Color3 object
  1499. */
  1500. Color3.prototype.multiply = function (otherColor) {
  1501. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1502. };
  1503. /**
  1504. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1505. * @param otherColor defines the second operand
  1506. * @param result defines the Color3 object where to store the result
  1507. * @returns the current Color3
  1508. */
  1509. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1510. result.r = this.r * otherColor.r;
  1511. result.g = this.g * otherColor.g;
  1512. result.b = this.b * otherColor.b;
  1513. return this;
  1514. };
  1515. /**
  1516. * Determines equality between Color3 objects
  1517. * @param otherColor defines the second operand
  1518. * @returns true if the rgb values are equal to the given ones
  1519. */
  1520. Color3.prototype.equals = function (otherColor) {
  1521. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1522. };
  1523. /**
  1524. * Determines equality between the current Color3 object and a set of r,b,g values
  1525. * @param r defines the red component to check
  1526. * @param g defines the green component to check
  1527. * @param b defines the blue component to check
  1528. * @returns true if the rgb values are equal to the given ones
  1529. */
  1530. Color3.prototype.equalsFloats = function (r, g, b) {
  1531. return this.r === r && this.g === g && this.b === b;
  1532. };
  1533. /**
  1534. * Multiplies in place each rgb value by scale
  1535. * @param scale defines the scaling factor
  1536. * @returns the updated Color3
  1537. */
  1538. Color3.prototype.scale = function (scale) {
  1539. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1540. };
  1541. /**
  1542. * Multiplies the rgb values by scale and stores the result into "result"
  1543. * @param scale defines the scaling factor
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the unmodified current Color3
  1546. */
  1547. Color3.prototype.scaleToRef = function (scale, result) {
  1548. result.r = this.r * scale;
  1549. result.g = this.g * scale;
  1550. result.b = this.b * scale;
  1551. return this;
  1552. };
  1553. /**
  1554. * Scale the current Color3 values by a factor and add the result to a given Color3
  1555. * @param scale defines the scale factor
  1556. * @param result defines color to store the result into
  1557. * @returns the unmodified current Color3
  1558. */
  1559. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1560. result.r += this.r * scale;
  1561. result.g += this.g * scale;
  1562. result.b += this.b * scale;
  1563. return this;
  1564. };
  1565. /**
  1566. * Clamps the rgb values by the min and max values and stores the result into "result"
  1567. * @param min defines minimum clamping value (default is 0)
  1568. * @param max defines maximum clamping value (default is 1)
  1569. * @param result defines color to store the result into
  1570. * @returns the original Color3
  1571. */
  1572. Color3.prototype.clampToRef = function (min, max, result) {
  1573. if (min === void 0) { min = 0; }
  1574. if (max === void 0) { max = 1; }
  1575. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1576. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1577. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1578. return this;
  1579. };
  1580. /**
  1581. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1582. * @param otherColor defines the second operand
  1583. * @returns the new Color3
  1584. */
  1585. Color3.prototype.add = function (otherColor) {
  1586. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1587. };
  1588. /**
  1589. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1590. * @param otherColor defines the second operand
  1591. * @param result defines Color3 object to store the result into
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.addToRef = function (otherColor, result) {
  1595. result.r = this.r + otherColor.r;
  1596. result.g = this.g + otherColor.g;
  1597. result.b = this.b + otherColor.b;
  1598. return this;
  1599. };
  1600. /**
  1601. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1602. * @param otherColor defines the second operand
  1603. * @returns the new Color3
  1604. */
  1605. Color3.prototype.subtract = function (otherColor) {
  1606. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1607. };
  1608. /**
  1609. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1610. * @param otherColor defines the second operand
  1611. * @param result defines Color3 object to store the result into
  1612. * @returns the unmodified current Color3
  1613. */
  1614. Color3.prototype.subtractToRef = function (otherColor, result) {
  1615. result.r = this.r - otherColor.r;
  1616. result.g = this.g - otherColor.g;
  1617. result.b = this.b - otherColor.b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Copy the current object
  1622. * @returns a new Color3 copied the current one
  1623. */
  1624. Color3.prototype.clone = function () {
  1625. return new Color3(this.r, this.g, this.b);
  1626. };
  1627. /**
  1628. * Copies the rgb values from the source in the current Color3
  1629. * @param source defines the source Color3 object
  1630. * @returns the updated Color3 object
  1631. */
  1632. Color3.prototype.copyFrom = function (source) {
  1633. this.r = source.r;
  1634. this.g = source.g;
  1635. this.b = source.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.copyFromFloats = function (r, g, b) {
  1646. this.r = r;
  1647. this.g = g;
  1648. this.b = b;
  1649. return this;
  1650. };
  1651. /**
  1652. * Updates the Color3 rgb values from the given floats
  1653. * @param r defines the red component to read from
  1654. * @param g defines the green component to read from
  1655. * @param b defines the blue component to read from
  1656. * @returns the current Color3 object
  1657. */
  1658. Color3.prototype.set = function (r, g, b) {
  1659. return this.copyFromFloats(r, g, b);
  1660. };
  1661. /**
  1662. * Compute the Color3 hexadecimal code as a string
  1663. * @returns a string containing the hexadecimal representation of the Color3 object
  1664. */
  1665. Color3.prototype.toHexString = function () {
  1666. var intR = (this.r * 255) | 0;
  1667. var intG = (this.g * 255) | 0;
  1668. var intB = (this.b * 255) | 0;
  1669. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1670. };
  1671. /**
  1672. * Computes a new Color3 converted from the current one to linear space
  1673. * @returns a new Color3 object
  1674. */
  1675. Color3.prototype.toLinearSpace = function () {
  1676. var convertedColor = new Color3();
  1677. this.toLinearSpaceToRef(convertedColor);
  1678. return convertedColor;
  1679. };
  1680. /**
  1681. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1682. * @param convertedColor defines the Color3 object where to store the linear space version
  1683. * @returns the unmodified Color3
  1684. */
  1685. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1686. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1687. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1688. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1689. return this;
  1690. };
  1691. /**
  1692. * Computes a new Color3 converted from the current one to gamma space
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.prototype.toGammaSpace = function () {
  1696. var convertedColor = new Color3();
  1697. this.toGammaSpaceToRef(convertedColor);
  1698. return convertedColor;
  1699. };
  1700. /**
  1701. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1702. * @param convertedColor defines the Color3 object where to store the gamma space version
  1703. * @returns the unmodified Color3
  1704. */
  1705. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1706. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1707. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1708. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1709. return this;
  1710. };
  1711. // Statics
  1712. /**
  1713. * Creates a new Color3 from the string containing valid hexadecimal values
  1714. * @param hex defines a string containing valid hexadecimal values
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.FromHexString = function (hex) {
  1718. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1719. return new Color3(0, 0, 0);
  1720. }
  1721. var r = parseInt(hex.substring(1, 3), 16);
  1722. var g = parseInt(hex.substring(3, 5), 16);
  1723. var b = parseInt(hex.substring(5, 7), 16);
  1724. return Color3.FromInts(r, g, b);
  1725. };
  1726. /**
  1727. * Creates a new Vector3 from the starting index of the given array
  1728. * @param array defines the source array
  1729. * @param offset defines an offset in the source array
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromArray = function (array, offset) {
  1733. if (offset === void 0) { offset = 0; }
  1734. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1735. };
  1736. /**
  1737. * Creates a new Color3 from integer values (< 256)
  1738. * @param r defines the red component to read from (value between 0 and 255)
  1739. * @param g defines the green component to read from (value between 0 and 255)
  1740. * @param b defines the blue component to read from (value between 0 and 255)
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromInts = function (r, g, b) {
  1744. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1745. };
  1746. /**
  1747. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1748. * @param start defines the start Color3 value
  1749. * @param end defines the end Color3 value
  1750. * @param amount defines the gradient value between start and end
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.Lerp = function (start, end, amount) {
  1754. var r = start.r + ((end.r - start.r) * amount);
  1755. var g = start.g + ((end.g - start.g) * amount);
  1756. var b = start.b + ((end.b - start.b) * amount);
  1757. return new Color3(r, g, b);
  1758. };
  1759. /**
  1760. * Returns a Color3 value containing a red color
  1761. * @returns a new Color3 object
  1762. */
  1763. Color3.Red = function () { return new Color3(1, 0, 0); };
  1764. /**
  1765. * Returns a Color3 value containing a green color
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Green = function () { return new Color3(0, 1, 0); };
  1769. /**
  1770. * Returns a Color3 value containing a blue color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1774. /**
  1775. * Returns a Color3 value containing a black color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Black = function () { return new Color3(0, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a white color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.White = function () { return new Color3(1, 1, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a purple color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1789. /**
  1790. * Returns a Color3 value containing a magenta color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a yellow color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1799. /**
  1800. * Returns a Color3 value containing a gray color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a teal color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1809. /**
  1810. * Returns a Color3 value containing a random color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1814. return Color3;
  1815. }());
  1816. BABYLON.Color3 = Color3;
  1817. /**
  1818. * Class used to hold a RBGA color
  1819. */
  1820. var Color4 = /** @class */ (function () {
  1821. /**
  1822. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1823. * @param r defines the red component (between 0 and 1, default is 0)
  1824. * @param g defines the green component (between 0 and 1, default is 0)
  1825. * @param b defines the blue component (between 0 and 1, default is 0)
  1826. * @param a defines the alpha component (between 0 and 1, default is 1)
  1827. */
  1828. function Color4(
  1829. /**
  1830. * Defines the red component (between 0 and 1, default is 0)
  1831. */
  1832. r,
  1833. /**
  1834. * Defines the green component (between 0 and 1, default is 0)
  1835. */
  1836. g,
  1837. /**
  1838. * Defines the blue component (between 0 and 1, default is 0)
  1839. */
  1840. b,
  1841. /**
  1842. * Defines the alpha component (between 0 and 1, default is 1)
  1843. */
  1844. a) {
  1845. if (r === void 0) { r = 0; }
  1846. if (g === void 0) { g = 0; }
  1847. if (b === void 0) { b = 0; }
  1848. if (a === void 0) { a = 1; }
  1849. this.r = r;
  1850. this.g = g;
  1851. this.b = b;
  1852. this.a = a;
  1853. }
  1854. // Operators
  1855. /**
  1856. * Adds in place the given Color4 values to the current Color4 object
  1857. * @param right defines the second operand
  1858. * @returns the current updated Color4 object
  1859. */
  1860. Color4.prototype.addInPlace = function (right) {
  1861. this.r += right.r;
  1862. this.g += right.g;
  1863. this.b += right.b;
  1864. this.a += right.a;
  1865. return this;
  1866. };
  1867. /**
  1868. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1869. * @returns the new array
  1870. */
  1871. Color4.prototype.asArray = function () {
  1872. var result = new Array();
  1873. this.toArray(result, 0);
  1874. return result;
  1875. };
  1876. /**
  1877. * Stores from the starting index in the given array the Color4 successive values
  1878. * @param array defines the array where to store the r,g,b components
  1879. * @param index defines an optional index in the target array to define where to start storing values
  1880. * @returns the current Color4 object
  1881. */
  1882. Color4.prototype.toArray = function (array, index) {
  1883. if (index === undefined) {
  1884. index = 0;
  1885. }
  1886. array[index] = this.r;
  1887. array[index + 1] = this.g;
  1888. array[index + 2] = this.b;
  1889. array[index + 3] = this.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1894. * @param right defines the second operand
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.add = function (right) {
  1898. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1899. };
  1900. /**
  1901. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1902. * @param right defines the second operand
  1903. * @returns a new Color4 object
  1904. */
  1905. Color4.prototype.subtract = function (right) {
  1906. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1907. };
  1908. /**
  1909. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1910. * @param right defines the second operand
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the current Color4 object
  1913. */
  1914. Color4.prototype.subtractToRef = function (right, result) {
  1915. result.r = this.r - right.r;
  1916. result.g = this.g - right.g;
  1917. result.b = this.b - right.b;
  1918. result.a = this.a - right.a;
  1919. return this;
  1920. };
  1921. /**
  1922. * Creates a new Color4 with the current Color4 values multiplied by scale
  1923. * @param scale defines the scaling factor to apply
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.scale = function (scale) {
  1927. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1928. };
  1929. /**
  1930. * Multiplies the current Color4 values by scale and stores the result in "result"
  1931. * @param scale defines the scaling factor to apply
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current unmodified Color4
  1934. */
  1935. Color4.prototype.scaleToRef = function (scale, result) {
  1936. result.r = this.r * scale;
  1937. result.g = this.g * scale;
  1938. result.b = this.b * scale;
  1939. result.a = this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Scale the current Color4 values by a factor and add the result to a given Color4
  1944. * @param scale defines the scale factor
  1945. * @param result defines the Color4 object where to store the result
  1946. * @returns the unmodified current Color4
  1947. */
  1948. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1949. result.r += this.r * scale;
  1950. result.g += this.g * scale;
  1951. result.b += this.b * scale;
  1952. result.a += this.a * scale;
  1953. return this;
  1954. };
  1955. /**
  1956. * Clamps the rgb values by the min and max values and stores the result into "result"
  1957. * @param min defines minimum clamping value (default is 0)
  1958. * @param max defines maximum clamping value (default is 1)
  1959. * @param result defines color to store the result into.
  1960. * @returns the cuurent Color4
  1961. */
  1962. Color4.prototype.clampToRef = function (min, max, result) {
  1963. if (min === void 0) { min = 0; }
  1964. if (max === void 0) { max = 1; }
  1965. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1966. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1967. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1968. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1969. return this;
  1970. };
  1971. /**
  1972. * Multipy an Color4 value by another and return a new Color4 object
  1973. * @param color defines the Color4 value to multiply by
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.multiply = function (color) {
  1977. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1978. };
  1979. /**
  1980. * Multipy a Color4 value by another and push the result in a reference value
  1981. * @param color defines the Color4 value to multiply by
  1982. * @param result defines the Color4 to fill the result in
  1983. * @returns the result Color4
  1984. */
  1985. Color4.prototype.multiplyToRef = function (color, result) {
  1986. result.r = this.r * color.r;
  1987. result.g = this.g * color.g;
  1988. result.b = this.b * color.b;
  1989. result.a = this.a * color.a;
  1990. return result;
  1991. };
  1992. /**
  1993. * Creates a string with the Color4 current values
  1994. * @returns the string representation of the Color4 object
  1995. */
  1996. Color4.prototype.toString = function () {
  1997. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1998. };
  1999. /**
  2000. * Returns the string "Color4"
  2001. * @returns "Color4"
  2002. */
  2003. Color4.prototype.getClassName = function () {
  2004. return "Color4";
  2005. };
  2006. /**
  2007. * Compute the Color4 hash code
  2008. * @returns an unique number that can be used to hash Color4 objects
  2009. */
  2010. Color4.prototype.getHashCode = function () {
  2011. var hash = this.r || 0;
  2012. hash = (hash * 397) ^ (this.g || 0);
  2013. hash = (hash * 397) ^ (this.b || 0);
  2014. hash = (hash * 397) ^ (this.a || 0);
  2015. return hash;
  2016. };
  2017. /**
  2018. * Creates a new Color4 copied from the current one
  2019. * @returns a new Color4 object
  2020. */
  2021. Color4.prototype.clone = function () {
  2022. return new Color4(this.r, this.g, this.b, this.a);
  2023. };
  2024. /**
  2025. * Copies the given Color4 values into the current one
  2026. * @param source defines the source Color4 object
  2027. * @returns the current updated Color4 object
  2028. */
  2029. Color4.prototype.copyFrom = function (source) {
  2030. this.r = source.r;
  2031. this.g = source.g;
  2032. this.b = source.b;
  2033. this.a = source.a;
  2034. return this;
  2035. };
  2036. /**
  2037. * Copies the given float values into the current one
  2038. * @param r defines the red component to read from
  2039. * @param g defines the green component to read from
  2040. * @param b defines the blue component to read from
  2041. * @param a defines the alpha component to read from
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2045. this.r = r;
  2046. this.g = g;
  2047. this.b = b;
  2048. this.a = a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the given float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.set = function (r, g, b, a) {
  2060. return this.copyFromFloats(r, g, b, a);
  2061. };
  2062. /**
  2063. * Compute the Color4 hexadecimal code as a string
  2064. * @returns a string containing the hexadecimal representation of the Color4 object
  2065. */
  2066. Color4.prototype.toHexString = function () {
  2067. var intR = (this.r * 255) | 0;
  2068. var intG = (this.g * 255) | 0;
  2069. var intB = (this.b * 255) | 0;
  2070. var intA = (this.a * 255) | 0;
  2071. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2072. };
  2073. /**
  2074. * Computes a new Color4 converted from the current one to linear space
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.prototype.toLinearSpace = function () {
  2078. var convertedColor = new Color4();
  2079. this.toLinearSpaceToRef(convertedColor);
  2080. return convertedColor;
  2081. };
  2082. /**
  2083. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2084. * @param convertedColor defines the Color4 object where to store the linear space version
  2085. * @returns the unmodified Color4
  2086. */
  2087. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2088. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2089. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2090. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2091. convertedColor.a = this.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Computes a new Color4 converted from the current one to gamma space
  2096. * @returns a new Color4 object
  2097. */
  2098. Color4.prototype.toGammaSpace = function () {
  2099. var convertedColor = new Color4();
  2100. this.toGammaSpaceToRef(convertedColor);
  2101. return convertedColor;
  2102. };
  2103. /**
  2104. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2105. * @param convertedColor defines the Color4 object where to store the gamma space version
  2106. * @returns the unmodified Color4
  2107. */
  2108. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2109. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2110. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2111. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2112. convertedColor.a = this.a;
  2113. return this;
  2114. };
  2115. // Statics
  2116. /**
  2117. * Creates a new Color4 from the string containing valid hexadecimal values
  2118. * @param hex defines a string containing valid hexadecimal values
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.FromHexString = function (hex) {
  2122. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2123. return new Color4(0.0, 0.0, 0.0, 0.0);
  2124. }
  2125. var r = parseInt(hex.substring(1, 3), 16);
  2126. var g = parseInt(hex.substring(3, 5), 16);
  2127. var b = parseInt(hex.substring(5, 7), 16);
  2128. var a = parseInt(hex.substring(7, 9), 16);
  2129. return Color4.FromInts(r, g, b, a);
  2130. };
  2131. /**
  2132. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2133. * @param left defines the start value
  2134. * @param right defines the end value
  2135. * @param amount defines the gradient factor
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.Lerp = function (left, right, amount) {
  2139. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2140. Color4.LerpToRef(left, right, amount, result);
  2141. return result;
  2142. };
  2143. /**
  2144. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2145. * @param left defines the start value
  2146. * @param right defines the end value
  2147. * @param amount defines the gradient factor
  2148. * @param result defines the Color4 object where to store data
  2149. */
  2150. Color4.LerpToRef = function (left, right, amount, result) {
  2151. result.r = left.r + (right.r - left.r) * amount;
  2152. result.g = left.g + (right.g - left.g) * amount;
  2153. result.b = left.b + (right.b - left.b) * amount;
  2154. result.a = left.a + (right.a - left.a) * amount;
  2155. };
  2156. /**
  2157. * Creates a new Color4 from the starting index element of the given array
  2158. * @param array defines the source array to read from
  2159. * @param offset defines the offset in the source array
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.FromArray = function (array, offset) {
  2163. if (offset === void 0) { offset = 0; }
  2164. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2165. };
  2166. /**
  2167. * Creates a new Color3 from integer values (< 256)
  2168. * @param r defines the red component to read from (value between 0 and 255)
  2169. * @param g defines the green component to read from (value between 0 and 255)
  2170. * @param b defines the blue component to read from (value between 0 and 255)
  2171. * @param a defines the alpha component to read from (value between 0 and 255)
  2172. * @returns a new Color3 object
  2173. */
  2174. Color4.FromInts = function (r, g, b, a) {
  2175. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2176. };
  2177. /**
  2178. * Check the content of a given array and convert it to an array containing RGBA data
  2179. * If the original array was already containing count * 4 values then it is returned directly
  2180. * @param colors defines the array to check
  2181. * @param count defines the number of RGBA data to expect
  2182. * @returns an array containing count * 4 values (RGBA)
  2183. */
  2184. Color4.CheckColors4 = function (colors, count) {
  2185. // Check if color3 was used
  2186. if (colors.length === count * 3) {
  2187. var colors4 = [];
  2188. for (var index = 0; index < colors.length; index += 3) {
  2189. var newIndex = (index / 3) * 4;
  2190. colors4[newIndex] = colors[index];
  2191. colors4[newIndex + 1] = colors[index + 1];
  2192. colors4[newIndex + 2] = colors[index + 2];
  2193. colors4[newIndex + 3] = 1.0;
  2194. }
  2195. return colors4;
  2196. }
  2197. return colors;
  2198. };
  2199. return Color4;
  2200. }());
  2201. BABYLON.Color4 = Color4;
  2202. /**
  2203. * Class representing a vector containing 2 coordinates
  2204. */
  2205. var Vector2 = /** @class */ (function () {
  2206. /**
  2207. * Creates a new Vector2 from the given x and y coordinates
  2208. * @param x defines the first coordinate
  2209. * @param y defines the second coordinate
  2210. */
  2211. function Vector2(
  2212. /** defines the first coordinate */
  2213. x,
  2214. /** defines the second coordinate */
  2215. y) {
  2216. this.x = x;
  2217. this.y = y;
  2218. }
  2219. /**
  2220. * Gets a string with the Vector2 coordinates
  2221. * @returns a string with the Vector2 coordinates
  2222. */
  2223. Vector2.prototype.toString = function () {
  2224. return "{X: " + this.x + " Y:" + this.y + "}";
  2225. };
  2226. /**
  2227. * Gets class name
  2228. * @returns the string "Vector2"
  2229. */
  2230. Vector2.prototype.getClassName = function () {
  2231. return "Vector2";
  2232. };
  2233. /**
  2234. * Gets current vector hash code
  2235. * @returns the Vector2 hash code as a number
  2236. */
  2237. Vector2.prototype.getHashCode = function () {
  2238. var hash = this.x || 0;
  2239. hash = (hash * 397) ^ (this.y || 0);
  2240. return hash;
  2241. };
  2242. // Operators
  2243. /**
  2244. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2245. * @param array defines the source array
  2246. * @param index defines the offset in source array
  2247. * @returns the current Vector2
  2248. */
  2249. Vector2.prototype.toArray = function (array, index) {
  2250. if (index === void 0) { index = 0; }
  2251. array[index] = this.x;
  2252. array[index + 1] = this.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Copy the current vector to an array
  2257. * @returns a new array with 2 elements: the Vector2 coordinates.
  2258. */
  2259. Vector2.prototype.asArray = function () {
  2260. var result = new Array();
  2261. this.toArray(result, 0);
  2262. return result;
  2263. };
  2264. /**
  2265. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2266. * @param source defines the source Vector2
  2267. * @returns the current updated Vector2
  2268. */
  2269. Vector2.prototype.copyFrom = function (source) {
  2270. this.x = source.x;
  2271. this.y = source.y;
  2272. return this;
  2273. };
  2274. /**
  2275. * Sets the Vector2 coordinates with the given floats
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. * @returns the current updated Vector2
  2279. */
  2280. Vector2.prototype.copyFromFloats = function (x, y) {
  2281. this.x = x;
  2282. this.y = y;
  2283. return this;
  2284. };
  2285. /**
  2286. * Sets the Vector2 coordinates with the given floats
  2287. * @param x defines the first coordinate
  2288. * @param y defines the second coordinate
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.set = function (x, y) {
  2292. return this.copyFromFloats(x, y);
  2293. };
  2294. /**
  2295. * Add another vector with the current one
  2296. * @param otherVector defines the other vector
  2297. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2298. */
  2299. Vector2.prototype.add = function (otherVector) {
  2300. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2301. };
  2302. /**
  2303. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2304. * @param otherVector defines the other vector
  2305. * @param result defines the target vector
  2306. * @returns the unmodified current Vector2
  2307. */
  2308. Vector2.prototype.addToRef = function (otherVector, result) {
  2309. result.x = this.x + otherVector.x;
  2310. result.y = this.y + otherVector.y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2315. * @param otherVector defines the other vector
  2316. * @returns the current updated Vector2
  2317. */
  2318. Vector2.prototype.addInPlace = function (otherVector) {
  2319. this.x += otherVector.x;
  2320. this.y += otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns a new Vector2
  2327. */
  2328. Vector2.prototype.addVector3 = function (otherVector) {
  2329. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2330. };
  2331. /**
  2332. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2333. * @param otherVector defines the other vector
  2334. * @returns a new Vector2
  2335. */
  2336. Vector2.prototype.subtract = function (otherVector) {
  2337. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2338. };
  2339. /**
  2340. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2341. * @param otherVector defines the other vector
  2342. * @param result defines the target vector
  2343. * @returns the unmodified current Vector2
  2344. */
  2345. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2346. result.x = this.x - otherVector.x;
  2347. result.y = this.y - otherVector.y;
  2348. return this;
  2349. };
  2350. /**
  2351. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2352. * @param otherVector defines the other vector
  2353. * @returns the current updated Vector2
  2354. */
  2355. Vector2.prototype.subtractInPlace = function (otherVector) {
  2356. this.x -= otherVector.x;
  2357. this.y -= otherVector.y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Multiplies in place the current Vector2 coordinates by the given ones
  2362. * @param otherVector defines the other vector
  2363. * @returns the current updated Vector2
  2364. */
  2365. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2366. this.x *= otherVector.x;
  2367. this.y *= otherVector.y;
  2368. return this;
  2369. };
  2370. /**
  2371. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2372. * @param otherVector defines the other vector
  2373. * @returns a new Vector2
  2374. */
  2375. Vector2.prototype.multiply = function (otherVector) {
  2376. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2377. };
  2378. /**
  2379. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @param result defines the target vector
  2382. * @returns the unmodified current Vector2
  2383. */
  2384. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2385. result.x = this.x * otherVector.x;
  2386. result.y = this.y * otherVector.y;
  2387. return this;
  2388. };
  2389. /**
  2390. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2391. * @param x defines the first coordinate
  2392. * @param y defines the second coordinate
  2393. * @returns a new Vector2
  2394. */
  2395. Vector2.prototype.multiplyByFloats = function (x, y) {
  2396. return new Vector2(this.x * x, this.y * y);
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.divide = function (otherVector) {
  2404. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2405. };
  2406. /**
  2407. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.divideToRef = function (otherVector, result) {
  2413. result.x = this.x / otherVector.x;
  2414. result.y = this.y / otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Divides the current Vector3 coordinates by the given ones
  2419. * @param otherVector defines the other vector
  2420. * @returns the current updated Vector2
  2421. */
  2422. Vector2.prototype.divideInPlace = function (otherVector) {
  2423. return this.divideToRef(otherVector, this);
  2424. };
  2425. /**
  2426. * Gets a new Vector2 with current Vector2 negated coordinates
  2427. * @returns a new Vector2
  2428. */
  2429. Vector2.prototype.negate = function () {
  2430. return new Vector2(-this.x, -this.y);
  2431. };
  2432. /**
  2433. * Multiply the Vector2 coordinates by scale
  2434. * @param scale defines the scaling factor
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.scaleInPlace = function (scale) {
  2438. this.x *= scale;
  2439. this.y *= scale;
  2440. return this;
  2441. };
  2442. /**
  2443. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2444. * @param scale defines the scaling factor
  2445. * @returns a new Vector2
  2446. */
  2447. Vector2.prototype.scale = function (scale) {
  2448. var result = new Vector2(0, 0);
  2449. this.scaleToRef(scale, result);
  2450. return result;
  2451. };
  2452. /**
  2453. * Scale the current Vector2 values by a factor to a given Vector2
  2454. * @param scale defines the scale factor
  2455. * @param result defines the Vector2 object where to store the result
  2456. * @returns the unmodified current Vector2
  2457. */
  2458. Vector2.prototype.scaleToRef = function (scale, result) {
  2459. result.x = this.x * scale;
  2460. result.y = this.y * scale;
  2461. return this;
  2462. };
  2463. /**
  2464. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2465. * @param scale defines the scale factor
  2466. * @param result defines the Vector2 object where to store the result
  2467. * @returns the unmodified current Vector2
  2468. */
  2469. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2470. result.x += this.x * scale;
  2471. result.y += this.y * scale;
  2472. return this;
  2473. };
  2474. /**
  2475. * Gets a boolean if two vectors are equals
  2476. * @param otherVector defines the other vector
  2477. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2478. */
  2479. Vector2.prototype.equals = function (otherVector) {
  2480. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2481. };
  2482. /**
  2483. * Gets a boolean if two vectors are equals (using an epsilon value)
  2484. * @param otherVector defines the other vector
  2485. * @param epsilon defines the minimal distance to consider equality
  2486. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2487. */
  2488. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2489. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2490. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2491. };
  2492. // Properties
  2493. /**
  2494. * Gets the length of the vector
  2495. * @returns the vector length (float)
  2496. */
  2497. Vector2.prototype.length = function () {
  2498. return Math.sqrt(this.x * this.x + this.y * this.y);
  2499. };
  2500. /**
  2501. * Gets the vector squared length
  2502. * @returns the vector squared length (float)
  2503. */
  2504. Vector2.prototype.lengthSquared = function () {
  2505. return (this.x * this.x + this.y * this.y);
  2506. };
  2507. // Methods
  2508. /**
  2509. * Normalize the vector
  2510. * @returns the current updated Vector2
  2511. */
  2512. Vector2.prototype.normalize = function () {
  2513. var len = this.length();
  2514. if (len === 0)
  2515. return this;
  2516. var num = 1.0 / len;
  2517. this.x *= num;
  2518. this.y *= num;
  2519. return this;
  2520. };
  2521. /**
  2522. * Gets a new Vector2 copied from the Vector2
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.clone = function () {
  2526. return new Vector2(this.x, this.y);
  2527. };
  2528. // Statics
  2529. /**
  2530. * Gets a new Vector2(0, 0)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.Zero = function () {
  2534. return new Vector2(0, 0);
  2535. };
  2536. /**
  2537. * Gets a new Vector2(1, 1)
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.One = function () {
  2541. return new Vector2(1, 1);
  2542. };
  2543. /**
  2544. * Gets a new Vector2 set from the given index element of the given array
  2545. * @param array defines the data source
  2546. * @param offset defines the offset in the data source
  2547. * @returns a new Vector2
  2548. */
  2549. Vector2.FromArray = function (array, offset) {
  2550. if (offset === void 0) { offset = 0; }
  2551. return new Vector2(array[offset], array[offset + 1]);
  2552. };
  2553. /**
  2554. * Sets "result" from the given index element of the given array
  2555. * @param array defines the data source
  2556. * @param offset defines the offset in the data source
  2557. * @param result defines the target vector
  2558. */
  2559. Vector2.FromArrayToRef = function (array, offset, result) {
  2560. result.x = array[offset];
  2561. result.y = array[offset + 1];
  2562. };
  2563. /**
  2564. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2565. * @param value1 defines 1st point of control
  2566. * @param value2 defines 2nd point of control
  2567. * @param value3 defines 3rd point of control
  2568. * @param value4 defines 4th point of control
  2569. * @param amount defines the interpolation factor
  2570. * @returns a new Vector2
  2571. */
  2572. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2573. var squared = amount * amount;
  2574. var cubed = amount * squared;
  2575. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2576. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2577. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2578. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2579. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2580. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2581. return new Vector2(x, y);
  2582. };
  2583. /**
  2584. * 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".
  2585. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2586. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2587. * @param value defines the value to clamp
  2588. * @param min defines the lower limit
  2589. * @param max defines the upper limit
  2590. * @returns a new Vector2
  2591. */
  2592. Vector2.Clamp = function (value, min, max) {
  2593. var x = value.x;
  2594. x = (x > max.x) ? max.x : x;
  2595. x = (x < min.x) ? min.x : x;
  2596. var y = value.y;
  2597. y = (y > max.y) ? max.y : y;
  2598. y = (y < min.y) ? min.y : y;
  2599. return new Vector2(x, y);
  2600. };
  2601. /**
  2602. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2603. * @param value1 defines the 1st control point
  2604. * @param tangent1 defines the outgoing tangent
  2605. * @param value2 defines the 2nd control point
  2606. * @param tangent2 defines the incoming tangent
  2607. * @param amount defines the interpolation factor
  2608. * @returns a new Vector2
  2609. */
  2610. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2611. var squared = amount * amount;
  2612. var cubed = amount * squared;
  2613. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2614. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2615. var part3 = (cubed - (2.0 * squared)) + amount;
  2616. var part4 = cubed - squared;
  2617. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2618. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2619. return new Vector2(x, y);
  2620. };
  2621. /**
  2622. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2623. * @param start defines the start vector
  2624. * @param end defines the end vector
  2625. * @param amount defines the interpolation factor
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Lerp = function (start, end, amount) {
  2629. var x = start.x + ((end.x - start.x) * amount);
  2630. var y = start.y + ((end.y - start.y) * amount);
  2631. return new Vector2(x, y);
  2632. };
  2633. /**
  2634. * Gets the dot product of the vector "left" and the vector "right"
  2635. * @param left defines first vector
  2636. * @param right defines second vector
  2637. * @returns the dot product (float)
  2638. */
  2639. Vector2.Dot = function (left, right) {
  2640. return left.x * right.x + left.y * right.y;
  2641. };
  2642. /**
  2643. * Returns a new Vector2 equal to the normalized given vector
  2644. * @param vector defines the vector to normalize
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.Normalize = function (vector) {
  2648. var newVector = vector.clone();
  2649. newVector.normalize();
  2650. return newVector;
  2651. };
  2652. /**
  2653. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2654. * @param left defines 1st vector
  2655. * @param right defines 2nd vector
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Minimize = function (left, right) {
  2659. var x = (left.x < right.x) ? left.x : right.x;
  2660. var y = (left.y < right.y) ? left.y : right.y;
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2665. * @param left defines 1st vector
  2666. * @param right defines 2nd vector
  2667. * @returns a new Vector2
  2668. */
  2669. Vector2.Maximize = function (left, right) {
  2670. var x = (left.x > right.x) ? left.x : right.x;
  2671. var y = (left.y > right.y) ? left.y : right.y;
  2672. return new Vector2(x, y);
  2673. };
  2674. /**
  2675. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2676. * @param vector defines the vector to transform
  2677. * @param transformation defines the matrix to apply
  2678. * @returns a new Vector2
  2679. */
  2680. Vector2.Transform = function (vector, transformation) {
  2681. var r = Vector2.Zero();
  2682. Vector2.TransformToRef(vector, transformation, r);
  2683. return r;
  2684. };
  2685. /**
  2686. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2687. * @param vector defines the vector to transform
  2688. * @param transformation defines the matrix to apply
  2689. * @param result defines the target vector
  2690. */
  2691. Vector2.TransformToRef = function (vector, transformation, result) {
  2692. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2693. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2694. result.x = x;
  2695. result.y = y;
  2696. };
  2697. /**
  2698. * Determines if a given vector is included in a triangle
  2699. * @param p defines the vector to test
  2700. * @param p0 defines 1st triangle point
  2701. * @param p1 defines 2nd triangle point
  2702. * @param p2 defines 3rd triangle point
  2703. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2704. */
  2705. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2706. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2707. var sign = a < 0 ? -1 : 1;
  2708. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2709. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2710. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2711. };
  2712. /**
  2713. * Gets the distance between the vectors "value1" and "value2"
  2714. * @param value1 defines first vector
  2715. * @param value2 defines second vector
  2716. * @returns the distance between vectors
  2717. */
  2718. Vector2.Distance = function (value1, value2) {
  2719. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2720. };
  2721. /**
  2722. * Returns the squared distance between the vectors "value1" and "value2"
  2723. * @param value1 defines first vector
  2724. * @param value2 defines second vector
  2725. * @returns the squared distance between vectors
  2726. */
  2727. Vector2.DistanceSquared = function (value1, value2) {
  2728. var x = value1.x - value2.x;
  2729. var y = value1.y - value2.y;
  2730. return (x * x) + (y * y);
  2731. };
  2732. /**
  2733. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2734. * @param value1 defines first vector
  2735. * @param value2 defines second vector
  2736. * @returns a new Vector2
  2737. */
  2738. Vector2.Center = function (value1, value2) {
  2739. var center = value1.add(value2);
  2740. center.scaleInPlace(0.5);
  2741. return center;
  2742. };
  2743. /**
  2744. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2745. * @param p defines the middle point
  2746. * @param segA defines one point of the segment
  2747. * @param segB defines the other point of the segment
  2748. * @returns the shortest distance
  2749. */
  2750. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2751. var l2 = Vector2.DistanceSquared(segA, segB);
  2752. if (l2 === 0.0) {
  2753. return Vector2.Distance(p, segA);
  2754. }
  2755. var v = segB.subtract(segA);
  2756. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2757. var proj = segA.add(v.multiplyByFloats(t, t));
  2758. return Vector2.Distance(p, proj);
  2759. };
  2760. return Vector2;
  2761. }());
  2762. BABYLON.Vector2 = Vector2;
  2763. /**
  2764. * Classed used to store (x,y,z) vector representation
  2765. * A Vector3 is the main object used in 3D geometry
  2766. * It can represent etiher the coordinates of a point the space, either a direction
  2767. * Reminder: Babylon.js uses a left handed forward facing system
  2768. */
  2769. var Vector3 = /** @class */ (function () {
  2770. /**
  2771. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2772. * @param x defines the first coordinates (on X axis)
  2773. * @param y defines the second coordinates (on Y axis)
  2774. * @param z defines the third coordinates (on Z axis)
  2775. */
  2776. function Vector3(
  2777. /**
  2778. * Defines the first coordinates (on X axis)
  2779. */
  2780. x,
  2781. /**
  2782. * Defines the second coordinates (on Y axis)
  2783. */
  2784. y,
  2785. /**
  2786. * Defines the third coordinates (on Z axis)
  2787. */
  2788. z) {
  2789. this.x = x;
  2790. this.y = y;
  2791. this.z = z;
  2792. }
  2793. /**
  2794. * Creates a string representation of the Vector3
  2795. * @returns a string with the Vector3 coordinates.
  2796. */
  2797. Vector3.prototype.toString = function () {
  2798. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2799. };
  2800. /**
  2801. * Gets the class name
  2802. * @returns the string "Vector3"
  2803. */
  2804. Vector3.prototype.getClassName = function () {
  2805. return "Vector3";
  2806. };
  2807. /**
  2808. * Creates the Vector3 hash code
  2809. * @returns a number which tends to be unique between Vector3 instances
  2810. */
  2811. Vector3.prototype.getHashCode = function () {
  2812. var hash = this.x || 0;
  2813. hash = (hash * 397) ^ (this.y || 0);
  2814. hash = (hash * 397) ^ (this.z || 0);
  2815. return hash;
  2816. };
  2817. // Operators
  2818. /**
  2819. * Creates an array containing three elements : the coordinates of the Vector3
  2820. * @returns a new array of numbers
  2821. */
  2822. Vector3.prototype.asArray = function () {
  2823. var result = [];
  2824. this.toArray(result, 0);
  2825. return result;
  2826. };
  2827. /**
  2828. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2829. * @param array defines the destination array
  2830. * @param index defines the offset in the destination array
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.toArray = function (array, index) {
  2834. if (index === void 0) { index = 0; }
  2835. array[index] = this.x;
  2836. array[index + 1] = this.y;
  2837. array[index + 2] = this.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2842. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2843. */
  2844. Vector3.prototype.toQuaternion = function () {
  2845. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2846. };
  2847. /**
  2848. * Adds the given vector to the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.addInPlace = function (otherVector) {
  2853. this.x += otherVector.x;
  2854. this.y += otherVector.y;
  2855. this.z += otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.add = function (otherVector) {
  2864. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2865. };
  2866. /**
  2867. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.addToRef = function (otherVector, result) {
  2873. result.x = this.x + otherVector.x;
  2874. result.y = this.y + otherVector.y;
  2875. result.z = this.z + otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Subtract the given vector from the current Vector3
  2880. * @param otherVector defines the second operand
  2881. * @returns the current updated Vector3
  2882. */
  2883. Vector3.prototype.subtractInPlace = function (otherVector) {
  2884. this.x -= otherVector.x;
  2885. this.y -= otherVector.y;
  2886. this.z -= otherVector.z;
  2887. return this;
  2888. };
  2889. /**
  2890. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtract = function (otherVector) {
  2895. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2896. };
  2897. /**
  2898. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2899. * @param otherVector defines the second operand
  2900. * @param result defines the Vector3 object where to store the result
  2901. * @returns the current Vector3
  2902. */
  2903. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2904. result.x = this.x - otherVector.x;
  2905. result.y = this.y - otherVector.y;
  2906. result.z = this.z - otherVector.z;
  2907. return this;
  2908. };
  2909. /**
  2910. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2911. * @param x defines the x coordinate of the operand
  2912. * @param y defines the y coordinate of the operand
  2913. * @param z defines the z coordinate of the operand
  2914. * @returns the resulting Vector3
  2915. */
  2916. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2917. return new Vector3(this.x - x, this.y - y, this.z - z);
  2918. };
  2919. /**
  2920. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2921. * @param x defines the x coordinate of the operand
  2922. * @param y defines the y coordinate of the operand
  2923. * @param z defines the z coordinate of the operand
  2924. * @param result defines the Vector3 object where to store the result
  2925. * @returns the current Vector3
  2926. */
  2927. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2928. result.x = this.x - x;
  2929. result.y = this.y - y;
  2930. result.z = this.z - z;
  2931. return this;
  2932. };
  2933. /**
  2934. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2935. * @returns a new Vector3
  2936. */
  2937. Vector3.prototype.negate = function () {
  2938. return new Vector3(-this.x, -this.y, -this.z);
  2939. };
  2940. /**
  2941. * Multiplies the Vector3 coordinates by the float "scale"
  2942. * @param scale defines the multiplier factor
  2943. * @returns the current updated Vector3
  2944. */
  2945. Vector3.prototype.scaleInPlace = function (scale) {
  2946. this.x *= scale;
  2947. this.y *= scale;
  2948. this.z *= scale;
  2949. return this;
  2950. };
  2951. /**
  2952. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2953. * @param scale defines the multiplier factor
  2954. * @returns a new Vector3
  2955. */
  2956. Vector3.prototype.scale = function (scale) {
  2957. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2958. };
  2959. /**
  2960. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2961. * @param scale defines the multiplier factor
  2962. * @param result defines the Vector3 object where to store the result
  2963. * @returns the current Vector3
  2964. */
  2965. Vector3.prototype.scaleToRef = function (scale, result) {
  2966. result.x = this.x * scale;
  2967. result.y = this.y * scale;
  2968. result.z = this.z * scale;
  2969. return this;
  2970. };
  2971. /**
  2972. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2973. * @param scale defines the scale factor
  2974. * @param result defines the Vector3 object where to store the result
  2975. * @returns the unmodified current Vector3
  2976. */
  2977. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2978. result.x += this.x * scale;
  2979. result.y += this.y * scale;
  2980. result.z += this.z * scale;
  2981. return this;
  2982. };
  2983. /**
  2984. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2985. * @param otherVector defines the second operand
  2986. * @returns true if both vectors are equals
  2987. */
  2988. Vector3.prototype.equals = function (otherVector) {
  2989. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2990. };
  2991. /**
  2992. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2993. * @param otherVector defines the second operand
  2994. * @param epsilon defines the minimal distance to define values as equals
  2995. * @returns true if both vectors are distant less than epsilon
  2996. */
  2997. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2998. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2999. 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);
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 coordinates equals the given floats
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @returns true if both vectors are equals
  3007. */
  3008. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3009. return this.x === x && this.y === y && this.z === z;
  3010. };
  3011. /**
  3012. * Multiplies the current Vector3 coordinates by the given ones
  3013. * @param otherVector defines the second operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3017. this.x *= otherVector.x;
  3018. this.y *= otherVector.y;
  3019. this.z *= otherVector.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3024. * @param otherVector defines the second operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiply = function (otherVector) {
  3028. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3029. };
  3030. /**
  3031. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3032. * @param otherVector defines the second operand
  3033. * @param result defines the Vector3 object where to store the result
  3034. * @returns the current Vector3
  3035. */
  3036. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3037. result.x = this.x * otherVector.x;
  3038. result.y = this.y * otherVector.y;
  3039. result.z = this.z * otherVector.z;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3044. * @param x defines the x coordinate of the operand
  3045. * @param y defines the y coordinate of the operand
  3046. * @param z defines the z coordinate of the operand
  3047. * @returns the new Vector3
  3048. */
  3049. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3050. return new Vector3(this.x * x, this.y * y, this.z * z);
  3051. };
  3052. /**
  3053. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3054. * @param otherVector defines the second operand
  3055. * @returns the new Vector3
  3056. */
  3057. Vector3.prototype.divide = function (otherVector) {
  3058. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3059. };
  3060. /**
  3061. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3062. * @param otherVector defines the second operand
  3063. * @param result defines the Vector3 object where to store the result
  3064. * @returns the current Vector3
  3065. */
  3066. Vector3.prototype.divideToRef = function (otherVector, result) {
  3067. result.x = this.x / otherVector.x;
  3068. result.y = this.y / otherVector.y;
  3069. result.z = this.z / otherVector.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Divides the current Vector3 coordinates by the given ones.
  3074. * @param otherVector defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.divideInPlace = function (otherVector) {
  3078. return this.divideToRef(otherVector, this);
  3079. };
  3080. /**
  3081. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3082. * @param other defines the second operand
  3083. * @returns the current updated Vector3
  3084. */
  3085. Vector3.prototype.minimizeInPlace = function (other) {
  3086. if (other.x < this.x)
  3087. this.x = other.x;
  3088. if (other.y < this.y)
  3089. this.y = other.y;
  3090. if (other.z < this.z)
  3091. this.z = other.z;
  3092. return this;
  3093. };
  3094. /**
  3095. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3096. * @param other defines the second operand
  3097. * @returns the current updated Vector3
  3098. */
  3099. Vector3.prototype.maximizeInPlace = function (other) {
  3100. if (other.x > this.x)
  3101. this.x = other.x;
  3102. if (other.y > this.y)
  3103. this.y = other.y;
  3104. if (other.z > this.z)
  3105. this.z = other.z;
  3106. return this;
  3107. };
  3108. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3109. /**
  3110. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3111. */
  3112. get: function () {
  3113. var absX = Math.abs(this.x);
  3114. var absY = Math.abs(this.y);
  3115. if (absX !== absY) {
  3116. return true;
  3117. }
  3118. var absZ = Math.abs(this.z);
  3119. if (absX !== absZ) {
  3120. return true;
  3121. }
  3122. if (absY !== absZ) {
  3123. return true;
  3124. }
  3125. return false;
  3126. },
  3127. enumerable: true,
  3128. configurable: true
  3129. });
  3130. // Properties
  3131. /**
  3132. * Gets the length of the Vector3
  3133. * @returns the length of the Vecto3
  3134. */
  3135. Vector3.prototype.length = function () {
  3136. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3137. };
  3138. /**
  3139. * Gets the squared length of the Vector3
  3140. * @returns squared length of the Vector3
  3141. */
  3142. Vector3.prototype.lengthSquared = function () {
  3143. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3144. };
  3145. /**
  3146. * Normalize the current Vector3.
  3147. * Please note that this is an in place operation.
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.normalize = function () {
  3151. var len = this.length();
  3152. if (len === 0 || len === 1.0)
  3153. return this;
  3154. var num = 1.0 / len;
  3155. this.x *= num;
  3156. this.y *= num;
  3157. this.z *= num;
  3158. return this;
  3159. };
  3160. /**
  3161. * Normalize the current Vector3 to a new vector
  3162. * @returns the new Vector3
  3163. */
  3164. Vector3.prototype.normalizeToNew = function () {
  3165. var normalized = new Vector3(0, 0, 0);
  3166. this.normalizeToRef(normalized);
  3167. return normalized;
  3168. };
  3169. /**
  3170. * Normalize the current Vector3 to the reference
  3171. * @param reference define the Vector3 to update
  3172. * @returns the updated Vector3
  3173. */
  3174. Vector3.prototype.normalizeToRef = function (reference) {
  3175. var len = this.length();
  3176. if (len === 0 || len === 1.0) {
  3177. reference.set(this.x, this.y, this.z);
  3178. return reference;
  3179. }
  3180. var scale = 1.0 / len;
  3181. this.scaleToRef(scale, reference);
  3182. return reference;
  3183. };
  3184. /**
  3185. * Creates a new Vector3 copied from the current Vector3
  3186. * @returns the new Vector3
  3187. */
  3188. Vector3.prototype.clone = function () {
  3189. return new Vector3(this.x, this.y, this.z);
  3190. };
  3191. /**
  3192. * Copies the given vector coordinates to the current Vector3 ones
  3193. * @param source defines the source Vector3
  3194. * @returns the current updated Vector3
  3195. */
  3196. Vector3.prototype.copyFrom = function (source) {
  3197. this.x = source.x;
  3198. this.y = source.y;
  3199. this.z = source.z;
  3200. return this;
  3201. };
  3202. /**
  3203. * Copies the given floats to the current Vector3 coordinates
  3204. * @param x defines the x coordinate of the operand
  3205. * @param y defines the y coordinate of the operand
  3206. * @param z defines the z coordinate of the operand
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3210. this.x = x;
  3211. this.y = y;
  3212. this.z = z;
  3213. return this;
  3214. };
  3215. /**
  3216. * Copies the given floats to the current Vector3 coordinates
  3217. * @param x defines the x coordinate of the operand
  3218. * @param y defines the y coordinate of the operand
  3219. * @param z defines the z coordinate of the operand
  3220. * @returns the current updated Vector3
  3221. */
  3222. Vector3.prototype.set = function (x, y, z) {
  3223. return this.copyFromFloats(x, y, z);
  3224. };
  3225. // Statics
  3226. /**
  3227. * Get the clip factor between two vectors
  3228. * @param vector0 defines the first operand
  3229. * @param vector1 defines the second operand
  3230. * @param axis defines the axis to use
  3231. * @param size defines the size along the axis
  3232. * @returns the clip factor
  3233. */
  3234. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3235. var d0 = Vector3.Dot(vector0, axis) - size;
  3236. var d1 = Vector3.Dot(vector1, axis) - size;
  3237. var s = d0 / (d0 - d1);
  3238. return s;
  3239. };
  3240. /**
  3241. * Get angle between two vectors
  3242. * @param vector0 angle between vector0 and vector1
  3243. * @param vector1 angle between vector0 and vector1
  3244. * @param normal direction of the normal
  3245. * @return the angle between vector0 and vector1
  3246. */
  3247. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3248. var v0 = vector0.clone().normalize();
  3249. var v1 = vector1.clone().normalize();
  3250. var dot = Vector3.Dot(v0, v1);
  3251. var n = Vector3.Cross(v0, v1);
  3252. if (Vector3.Dot(n, normal) > 0) {
  3253. return Math.acos(dot);
  3254. }
  3255. return -Math.acos(dot);
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @returns the new Vector3
  3262. */
  3263. Vector3.FromArray = function (array, offset) {
  3264. if (!offset) {
  3265. offset = 0;
  3266. }
  3267. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3268. };
  3269. /**
  3270. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3271. * This function is deprecated. Use FromArray instead
  3272. * @param array defines the source array
  3273. * @param offset defines the offset in the source array
  3274. * @returns the new Vector3
  3275. */
  3276. Vector3.FromFloatArray = function (array, offset) {
  3277. return Vector3.FromArray(array, offset);
  3278. };
  3279. /**
  3280. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3281. * @param array defines the source array
  3282. * @param offset defines the offset in the source array
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. };
  3290. /**
  3291. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3292. * This function is deprecated. Use FromArrayToRef instead.
  3293. * @param array defines the source array
  3294. * @param offset defines the offset in the source array
  3295. * @param result defines the Vector3 where to store the result
  3296. */
  3297. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3298. return Vector3.FromArrayToRef(array, offset, result);
  3299. };
  3300. /**
  3301. * Sets the given vector "result" with the given floats.
  3302. * @param x defines the x coordinate of the source
  3303. * @param y defines the y coordinate of the source
  3304. * @param z defines the z coordinate of the source
  3305. * @param result defines the Vector3 where to store the result
  3306. */
  3307. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3308. result.x = x;
  3309. result.y = y;
  3310. result.z = z;
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3314. * @returns a new empty Vector3
  3315. */
  3316. Vector3.Zero = function () {
  3317. return new Vector3(0.0, 0.0, 0.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3321. * @returns a new unit Vector3
  3322. */
  3323. Vector3.One = function () {
  3324. return new Vector3(1.0, 1.0, 1.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3328. * @returns a new up Vector3
  3329. */
  3330. Vector3.Up = function () {
  3331. return new Vector3(0.0, 1.0, 0.0);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3335. * @returns a new forward Vector3
  3336. */
  3337. Vector3.Forward = function () {
  3338. return new Vector3(0.0, 0.0, 1.0);
  3339. };
  3340. /**
  3341. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3342. * @returns a new right Vector3
  3343. */
  3344. Vector3.Right = function () {
  3345. return new Vector3(1.0, 0.0, 0.0);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3349. * @returns a new left Vector3
  3350. */
  3351. Vector3.Left = function () {
  3352. return new Vector3(-1.0, 0.0, 0.0);
  3353. };
  3354. /**
  3355. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3356. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3357. * @param vector defines the Vector3 to transform
  3358. * @param transformation defines the transformation matrix
  3359. * @returns the transformed Vector3
  3360. */
  3361. Vector3.TransformCoordinates = function (vector, transformation) {
  3362. var result = Vector3.Zero();
  3363. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3364. return result;
  3365. };
  3366. /**
  3367. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3368. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3374. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3375. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3376. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3377. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3378. result.x = x / w;
  3379. result.y = y / w;
  3380. result.z = z / w;
  3381. };
  3382. /**
  3383. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3384. * This method computes tranformed coordinates only, not transformed direction vectors
  3385. * @param x define the x coordinate of the source vector
  3386. * @param y define the y coordinate of the source vector
  3387. * @param z define the z coordinate of the source vector
  3388. * @param transformation defines the transformation matrix
  3389. * @param result defines the Vector3 where to store the result
  3390. */
  3391. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3392. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3393. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3394. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3395. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3396. result.x = rx / rw;
  3397. result.y = ry / rw;
  3398. result.z = rz / rw;
  3399. };
  3400. /**
  3401. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3402. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3403. * @param vector defines the Vector3 to transform
  3404. * @param transformation defines the transformation matrix
  3405. * @returns the new Vector3
  3406. */
  3407. Vector3.TransformNormal = function (vector, transformation) {
  3408. var result = Vector3.Zero();
  3409. Vector3.TransformNormalToRef(vector, transformation, result);
  3410. return result;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param vector defines the Vector3 to transform
  3416. * @param transformation defines the transformation matrix
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3420. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3421. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3422. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3423. result.x = x;
  3424. result.y = y;
  3425. result.z = z;
  3426. };
  3427. /**
  3428. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3429. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3430. * @param x define the x coordinate of the source vector
  3431. * @param y define the y coordinate of the source vector
  3432. * @param z define the z coordinate of the source vector
  3433. * @param transformation defines the transformation matrix
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3437. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3438. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3439. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3443. * @param value1 defines the first control point
  3444. * @param value2 defines the second control point
  3445. * @param value3 defines the third control point
  3446. * @param value4 defines the fourth control point
  3447. * @param amount defines the amount on the spline to use
  3448. * @returns the new Vector3
  3449. */
  3450. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3451. var squared = amount * amount;
  3452. var cubed = amount * squared;
  3453. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3454. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3455. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3456. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3457. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3458. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3459. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3460. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3461. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3462. return new Vector3(x, y, z);
  3463. };
  3464. /**
  3465. * 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"
  3466. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3467. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3468. * @param value defines the current value
  3469. * @param min defines the lower range value
  3470. * @param max defines the upper range value
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.Clamp = function (value, min, max) {
  3474. var x = value.x;
  3475. x = (x > max.x) ? max.x : x;
  3476. x = (x < min.x) ? min.x : x;
  3477. var y = value.y;
  3478. y = (y > max.y) ? max.y : y;
  3479. y = (y < min.y) ? min.y : y;
  3480. var z = value.z;
  3481. z = (z > max.z) ? max.z : z;
  3482. z = (z < min.z) ? min.z : z;
  3483. return new Vector3(x, y, z);
  3484. };
  3485. /**
  3486. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3487. * @param value1 defines the first control point
  3488. * @param tangent1 defines the first tangent vector
  3489. * @param value2 defines the second control point
  3490. * @param tangent2 defines the second tangent vector
  3491. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3492. * @returns the new Vector3
  3493. */
  3494. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3495. var squared = amount * amount;
  3496. var cubed = amount * squared;
  3497. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3498. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3499. var part3 = (cubed - (2.0 * squared)) + amount;
  3500. var part4 = cubed - squared;
  3501. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3502. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3503. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3504. return new Vector3(x, y, z);
  3505. };
  3506. /**
  3507. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3508. * @param start defines the start value
  3509. * @param end defines the end value
  3510. * @param amount max defines amount between both (between 0 and 1)
  3511. * @returns the new Vector3
  3512. */
  3513. Vector3.Lerp = function (start, end, amount) {
  3514. var result = new Vector3(0, 0, 0);
  3515. Vector3.LerpToRef(start, end, amount, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3520. * @param start defines the start value
  3521. * @param end defines the end value
  3522. * @param amount max defines amount between both (between 0 and 1)
  3523. * @param result defines the Vector3 where to store the result
  3524. */
  3525. Vector3.LerpToRef = function (start, end, amount, result) {
  3526. result.x = start.x + ((end.x - start.x) * amount);
  3527. result.y = start.y + ((end.y - start.y) * amount);
  3528. result.z = start.z + ((end.z - start.z) * amount);
  3529. };
  3530. /**
  3531. * Returns the dot product (float) between the vectors "left" and "right"
  3532. * @param left defines the left operand
  3533. * @param right defines the right operand
  3534. * @returns the dot product
  3535. */
  3536. Vector3.Dot = function (left, right) {
  3537. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3538. };
  3539. /**
  3540. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3541. * The cross product is then orthogonal to both "left" and "right"
  3542. * @param left defines the left operand
  3543. * @param right defines the right operand
  3544. * @returns the cross product
  3545. */
  3546. Vector3.Cross = function (left, right) {
  3547. var result = Vector3.Zero();
  3548. Vector3.CrossToRef(left, right, result);
  3549. return result;
  3550. };
  3551. /**
  3552. * Sets the given vector "result" with the cross product of "left" and "right"
  3553. * The cross product is then orthogonal to both "left" and "right"
  3554. * @param left defines the left operand
  3555. * @param right defines the right operand
  3556. * @param result defines the Vector3 where to store the result
  3557. */
  3558. Vector3.CrossToRef = function (left, right, result) {
  3559. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3560. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3561. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3562. result.copyFrom(MathTmp.Vector3[0]);
  3563. };
  3564. /**
  3565. * Returns a new Vector3 as the normalization of the given vector
  3566. * @param vector defines the Vector3 to normalize
  3567. * @returns the new Vector3
  3568. */
  3569. Vector3.Normalize = function (vector) {
  3570. var result = Vector3.Zero();
  3571. Vector3.NormalizeToRef(vector, result);
  3572. return result;
  3573. };
  3574. /**
  3575. * Sets the given vector "result" with the normalization of the given first vector
  3576. * @param vector defines the Vector3 to normalize
  3577. * @param result defines the Vector3 where to store the result
  3578. */
  3579. Vector3.NormalizeToRef = function (vector, result) {
  3580. result.copyFrom(vector);
  3581. result.normalize();
  3582. };
  3583. /**
  3584. * Project a Vector3 onto screen space
  3585. * @param vector defines the Vector3 to project
  3586. * @param world defines the world matrix to use
  3587. * @param transform defines the transform (view x projection) matrix to use
  3588. * @param viewport defines the screen viewport to use
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Project = function (vector, world, transform, viewport) {
  3592. var cw = viewport.width;
  3593. var ch = viewport.height;
  3594. var cx = viewport.x;
  3595. var cy = viewport.y;
  3596. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3597. 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);
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.multiplyToRef(viewportMatrix, matrix);
  3601. return Vector3.TransformCoordinates(vector, matrix);
  3602. };
  3603. /**
  3604. * Unproject from screen space to object space
  3605. * @param source defines the screen space Vector3 to use
  3606. * @param viewportWidth defines the current width of the viewport
  3607. * @param viewportHeight defines the current height of the viewport
  3608. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3609. * @param transform defines the transform (view x projection) matrix to use
  3610. * @returns the new Vector3
  3611. */
  3612. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3613. var matrix = MathTmp.Matrix[0];
  3614. world.multiplyToRef(transform, matrix);
  3615. matrix.invert();
  3616. source.x = source.x / viewportWidth * 2 - 1;
  3617. source.y = -(source.y / viewportHeight * 2 - 1);
  3618. var vector = Vector3.TransformCoordinates(source, matrix);
  3619. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3620. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3621. vector = vector.scale(1.0 / num);
  3622. }
  3623. return vector;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3636. var result = Vector3.Zero();
  3637. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Unproject from screen space to object space
  3642. * @param source defines the screen space Vector3 to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3652. };
  3653. /**
  3654. * Unproject from screen space to object space
  3655. * @param sourceX defines the screen space x coordinate to use
  3656. * @param sourceY defines the screen space y coordinate to use
  3657. * @param sourceZ defines the screen space z coordinate to use
  3658. * @param viewportWidth defines the current width of the viewport
  3659. * @param viewportHeight defines the current height of the viewport
  3660. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3661. * @param view defines the view matrix to use
  3662. * @param projection defines the projection matrix to use
  3663. * @param result defines the Vector3 where to store the result
  3664. */
  3665. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3666. var matrix = MathTmp.Matrix[0];
  3667. world.multiplyToRef(view, matrix);
  3668. matrix.multiplyToRef(projection, matrix);
  3669. matrix.invert();
  3670. var screenSource = MathTmp.Vector3[0];
  3671. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3672. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3673. screenSource.z = 2 * sourceZ - 1.0;
  3674. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3675. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3676. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3677. result.scaleInPlace(1.0 / num);
  3678. }
  3679. };
  3680. /**
  3681. * Gets the minimal coordinate values between two Vector3
  3682. * @param left defines the first operand
  3683. * @param right defines the second operand
  3684. * @returns the new Vector3
  3685. */
  3686. Vector3.Minimize = function (left, right) {
  3687. var min = left.clone();
  3688. min.minimizeInPlace(right);
  3689. return min;
  3690. };
  3691. /**
  3692. * Gets the maximal coordinate values between two Vector3
  3693. * @param left defines the first operand
  3694. * @param right defines the second operand
  3695. * @returns the new Vector3
  3696. */
  3697. Vector3.Maximize = function (left, right) {
  3698. var max = left.clone();
  3699. max.maximizeInPlace(right);
  3700. return max;
  3701. };
  3702. /**
  3703. * Returns the distance between the vectors "value1" and "value2"
  3704. * @param value1 defines the first operand
  3705. * @param value2 defines the second operand
  3706. * @returns the distance
  3707. */
  3708. Vector3.Distance = function (value1, value2) {
  3709. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3710. };
  3711. /**
  3712. * Returns the squared distance between the vectors "value1" and "value2"
  3713. * @param value1 defines the first operand
  3714. * @param value2 defines the second operand
  3715. * @returns the squared distance
  3716. */
  3717. Vector3.DistanceSquared = function (value1, value2) {
  3718. var x = value1.x - value2.x;
  3719. var y = value1.y - value2.y;
  3720. var z = value1.z - value2.z;
  3721. return (x * x) + (y * y) + (z * z);
  3722. };
  3723. /**
  3724. * Returns a new Vector3 located at the center between "value1" and "value2"
  3725. * @param value1 defines the first operand
  3726. * @param value2 defines the second operand
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Center = function (value1, value2) {
  3730. var center = value1.add(value2);
  3731. center.scaleInPlace(0.5);
  3732. return center;
  3733. };
  3734. /**
  3735. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3736. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3737. * to something in order to rotate it from its local system to the given target system
  3738. * Note: axis1, axis2 and axis3 are normalized during this operation
  3739. * @param axis1 defines the first axis
  3740. * @param axis2 defines the second axis
  3741. * @param axis3 defines the third axis
  3742. * @returns a new Vector3
  3743. */
  3744. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3745. var rotation = Vector3.Zero();
  3746. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3747. return rotation;
  3748. };
  3749. /**
  3750. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3751. * @param axis1 defines the first axis
  3752. * @param axis2 defines the second axis
  3753. * @param axis3 defines the third axis
  3754. * @param ref defines the Vector3 where to store the result
  3755. */
  3756. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3757. var quat = MathTmp.Quaternion[0];
  3758. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3759. quat.toEulerAnglesToRef(ref);
  3760. };
  3761. return Vector3;
  3762. }());
  3763. BABYLON.Vector3 = Vector3;
  3764. //Vector4 class created for EulerAngle class conversion to Quaternion
  3765. var Vector4 = /** @class */ (function () {
  3766. /**
  3767. * Creates a Vector4 object from the given floats.
  3768. */
  3769. function Vector4(x, y, z, w) {
  3770. this.x = x;
  3771. this.y = y;
  3772. this.z = z;
  3773. this.w = w;
  3774. }
  3775. /**
  3776. * Returns the string with the Vector4 coordinates.
  3777. */
  3778. Vector4.prototype.toString = function () {
  3779. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3780. };
  3781. /**
  3782. * Returns the string "Vector4".
  3783. */
  3784. Vector4.prototype.getClassName = function () {
  3785. return "Vector4";
  3786. };
  3787. /**
  3788. * Returns the Vector4 hash code.
  3789. */
  3790. Vector4.prototype.getHashCode = function () {
  3791. var hash = this.x || 0;
  3792. hash = (hash * 397) ^ (this.y || 0);
  3793. hash = (hash * 397) ^ (this.z || 0);
  3794. hash = (hash * 397) ^ (this.w || 0);
  3795. return hash;
  3796. };
  3797. // Operators
  3798. /**
  3799. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3800. */
  3801. Vector4.prototype.asArray = function () {
  3802. var result = new Array();
  3803. this.toArray(result, 0);
  3804. return result;
  3805. };
  3806. /**
  3807. * Populates the given array from the given index with the Vector4 coordinates.
  3808. * Returns the Vector4.
  3809. */
  3810. Vector4.prototype.toArray = function (array, index) {
  3811. if (index === undefined) {
  3812. index = 0;
  3813. }
  3814. array[index] = this.x;
  3815. array[index + 1] = this.y;
  3816. array[index + 2] = this.z;
  3817. array[index + 3] = this.w;
  3818. return this;
  3819. };
  3820. /**
  3821. * Adds the given vector to the current Vector4.
  3822. * Returns the updated Vector4.
  3823. */
  3824. Vector4.prototype.addInPlace = function (otherVector) {
  3825. this.x += otherVector.x;
  3826. this.y += otherVector.y;
  3827. this.z += otherVector.z;
  3828. this.w += otherVector.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3833. */
  3834. Vector4.prototype.add = function (otherVector) {
  3835. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3836. };
  3837. /**
  3838. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3839. * Returns the current Vector4.
  3840. */
  3841. Vector4.prototype.addToRef = function (otherVector, result) {
  3842. result.x = this.x + otherVector.x;
  3843. result.y = this.y + otherVector.y;
  3844. result.z = this.z + otherVector.z;
  3845. result.w = this.w + otherVector.w;
  3846. return this;
  3847. };
  3848. /**
  3849. * Subtract in place the given vector from the current Vector4.
  3850. * Returns the updated Vector4.
  3851. */
  3852. Vector4.prototype.subtractInPlace = function (otherVector) {
  3853. this.x -= otherVector.x;
  3854. this.y -= otherVector.y;
  3855. this.z -= otherVector.z;
  3856. this.w -= otherVector.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3861. */
  3862. Vector4.prototype.subtract = function (otherVector) {
  3863. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3864. };
  3865. /**
  3866. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3870. result.x = this.x - otherVector.x;
  3871. result.y = this.y - otherVector.y;
  3872. result.z = this.z - otherVector.z;
  3873. result.w = this.w - otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3878. */
  3879. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3880. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3881. };
  3882. /**
  3883. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3884. * Returns the current Vector4.
  3885. */
  3886. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3887. result.x = this.x - x;
  3888. result.y = this.y - y;
  3889. result.z = this.z - z;
  3890. result.w = this.w - w;
  3891. return this;
  3892. };
  3893. /**
  3894. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3895. */
  3896. Vector4.prototype.negate = function () {
  3897. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3898. };
  3899. /**
  3900. * Multiplies the current Vector4 coordinates by scale (float).
  3901. * Returns the updated Vector4.
  3902. */
  3903. Vector4.prototype.scaleInPlace = function (scale) {
  3904. this.x *= scale;
  3905. this.y *= scale;
  3906. this.z *= scale;
  3907. this.w *= scale;
  3908. return this;
  3909. };
  3910. /**
  3911. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3912. */
  3913. Vector4.prototype.scale = function (scale) {
  3914. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3915. };
  3916. /**
  3917. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3918. * Returns the current Vector4.
  3919. */
  3920. Vector4.prototype.scaleToRef = function (scale, result) {
  3921. result.x = this.x * scale;
  3922. result.y = this.y * scale;
  3923. result.z = this.z * scale;
  3924. result.w = this.w * scale;
  3925. return this;
  3926. };
  3927. /**
  3928. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3929. * @param scale defines the scale factor
  3930. * @param result defines the Vector4 object where to store the result
  3931. * @returns the unmodified current Vector4
  3932. */
  3933. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3934. result.x += this.x * scale;
  3935. result.y += this.y * scale;
  3936. result.z += this.z * scale;
  3937. result.w += this.w * scale;
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3942. */
  3943. Vector4.prototype.equals = function (otherVector) {
  3944. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3945. };
  3946. /**
  3947. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3948. */
  3949. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3950. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3951. return otherVector
  3952. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3953. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3954. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3955. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3956. };
  3957. /**
  3958. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3959. */
  3960. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3961. return this.x === x && this.y === y && this.z === z && this.w === w;
  3962. };
  3963. /**
  3964. * Multiplies in place the current Vector4 by the given one.
  3965. * Returns the updated Vector4.
  3966. */
  3967. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3968. this.x *= otherVector.x;
  3969. this.y *= otherVector.y;
  3970. this.z *= otherVector.z;
  3971. this.w *= otherVector.w;
  3972. return this;
  3973. };
  3974. /**
  3975. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3976. */
  3977. Vector4.prototype.multiply = function (otherVector) {
  3978. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3979. };
  3980. /**
  3981. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3982. * Returns the current Vector4.
  3983. */
  3984. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3985. result.x = this.x * otherVector.x;
  3986. result.y = this.y * otherVector.y;
  3987. result.z = this.z * otherVector.z;
  3988. result.w = this.w * otherVector.w;
  3989. return this;
  3990. };
  3991. /**
  3992. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3993. */
  3994. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3995. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3996. };
  3997. /**
  3998. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3999. */
  4000. Vector4.prototype.divide = function (otherVector) {
  4001. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4002. };
  4003. /**
  4004. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4005. * Returns the current Vector4.
  4006. */
  4007. Vector4.prototype.divideToRef = function (otherVector, result) {
  4008. result.x = this.x / otherVector.x;
  4009. result.y = this.y / otherVector.y;
  4010. result.z = this.z / otherVector.z;
  4011. result.w = this.w / otherVector.w;
  4012. return this;
  4013. };
  4014. /**
  4015. * Divides the current Vector3 coordinates by the given ones.
  4016. * @returns the updated Vector3.
  4017. */
  4018. Vector4.prototype.divideInPlace = function (otherVector) {
  4019. return this.divideToRef(otherVector, this);
  4020. };
  4021. /**
  4022. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4023. * @param other defines the second operand
  4024. * @returns the current updated Vector4
  4025. */
  4026. Vector4.prototype.minimizeInPlace = function (other) {
  4027. if (other.x < this.x)
  4028. this.x = other.x;
  4029. if (other.y < this.y)
  4030. this.y = other.y;
  4031. if (other.z < this.z)
  4032. this.z = other.z;
  4033. if (other.w < this.w)
  4034. this.w = other.w;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4039. * @param other defines the second operand
  4040. * @returns the current updated Vector4
  4041. */
  4042. Vector4.prototype.maximizeInPlace = function (other) {
  4043. if (other.x > this.x)
  4044. this.x = other.x;
  4045. if (other.y > this.y)
  4046. this.y = other.y;
  4047. if (other.z > this.z)
  4048. this.z = other.z;
  4049. if (other.w > this.w)
  4050. this.w = other.w;
  4051. return this;
  4052. };
  4053. // Properties
  4054. /**
  4055. * Returns the Vector4 length (float).
  4056. */
  4057. Vector4.prototype.length = function () {
  4058. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4059. };
  4060. /**
  4061. * Returns the Vector4 squared length (float).
  4062. */
  4063. Vector4.prototype.lengthSquared = function () {
  4064. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4065. };
  4066. // Methods
  4067. /**
  4068. * Normalizes in place the Vector4.
  4069. * Returns the updated Vector4.
  4070. */
  4071. Vector4.prototype.normalize = function () {
  4072. var len = this.length();
  4073. if (len === 0)
  4074. return this;
  4075. var num = 1.0 / len;
  4076. this.x *= num;
  4077. this.y *= num;
  4078. this.z *= num;
  4079. this.w *= num;
  4080. return this;
  4081. };
  4082. /**
  4083. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4084. */
  4085. Vector4.prototype.toVector3 = function () {
  4086. return new Vector3(this.x, this.y, this.z);
  4087. };
  4088. /**
  4089. * Returns a new Vector4 copied from the current one.
  4090. */
  4091. Vector4.prototype.clone = function () {
  4092. return new Vector4(this.x, this.y, this.z, this.w);
  4093. };
  4094. /**
  4095. * Updates the current Vector4 with the given one coordinates.
  4096. * Returns the updated Vector4.
  4097. */
  4098. Vector4.prototype.copyFrom = function (source) {
  4099. this.x = source.x;
  4100. this.y = source.y;
  4101. this.z = source.z;
  4102. this.w = source.w;
  4103. return this;
  4104. };
  4105. /**
  4106. * Updates the current Vector4 coordinates with the given floats.
  4107. * Returns the updated Vector4.
  4108. */
  4109. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4110. this.x = x;
  4111. this.y = y;
  4112. this.z = z;
  4113. this.w = w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the current Vector4 coordinates with the given floats.
  4118. * Returns the updated Vector4.
  4119. */
  4120. Vector4.prototype.set = function (x, y, z, w) {
  4121. return this.copyFromFloats(x, y, z, w);
  4122. };
  4123. // Statics
  4124. /**
  4125. * Returns a new Vector4 set from the starting index of the given array.
  4126. */
  4127. Vector4.FromArray = function (array, offset) {
  4128. if (!offset) {
  4129. offset = 0;
  4130. }
  4131. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" from the starting index of the given array.
  4135. */
  4136. Vector4.FromArrayToRef = function (array, offset, result) {
  4137. result.x = array[offset];
  4138. result.y = array[offset + 1];
  4139. result.z = array[offset + 2];
  4140. result.w = array[offset + 3];
  4141. };
  4142. /**
  4143. * Updates the given vector "result" from the starting index of the given Float32Array.
  4144. */
  4145. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4146. Vector4.FromArrayToRef(array, offset, result);
  4147. };
  4148. /**
  4149. * Updates the given vector "result" coordinates from the given floats.
  4150. */
  4151. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4152. result.x = x;
  4153. result.y = y;
  4154. result.z = z;
  4155. result.w = w;
  4156. };
  4157. /**
  4158. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4159. */
  4160. Vector4.Zero = function () {
  4161. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4162. };
  4163. /**
  4164. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4165. */
  4166. Vector4.One = function () {
  4167. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4168. };
  4169. /**
  4170. * Returns a new normalized Vector4 from the given one.
  4171. */
  4172. Vector4.Normalize = function (vector) {
  4173. var result = Vector4.Zero();
  4174. Vector4.NormalizeToRef(vector, result);
  4175. return result;
  4176. };
  4177. /**
  4178. * Updates the given vector "result" from the normalization of the given one.
  4179. */
  4180. Vector4.NormalizeToRef = function (vector, result) {
  4181. result.copyFrom(vector);
  4182. result.normalize();
  4183. };
  4184. Vector4.Minimize = function (left, right) {
  4185. var min = left.clone();
  4186. min.minimizeInPlace(right);
  4187. return min;
  4188. };
  4189. Vector4.Maximize = function (left, right) {
  4190. var max = left.clone();
  4191. max.maximizeInPlace(right);
  4192. return max;
  4193. };
  4194. /**
  4195. * Returns the distance (float) between the vectors "value1" and "value2".
  4196. */
  4197. Vector4.Distance = function (value1, value2) {
  4198. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4199. };
  4200. /**
  4201. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4202. */
  4203. Vector4.DistanceSquared = function (value1, value2) {
  4204. var x = value1.x - value2.x;
  4205. var y = value1.y - value2.y;
  4206. var z = value1.z - value2.z;
  4207. var w = value1.w - value2.w;
  4208. return (x * x) + (y * y) + (z * z) + (w * w);
  4209. };
  4210. /**
  4211. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4212. */
  4213. Vector4.Center = function (value1, value2) {
  4214. var center = value1.add(value2);
  4215. center.scaleInPlace(0.5);
  4216. return center;
  4217. };
  4218. /**
  4219. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4220. * This methods computes transformed normalized direction vectors only.
  4221. */
  4222. Vector4.TransformNormal = function (vector, transformation) {
  4223. var result = Vector4.Zero();
  4224. Vector4.TransformNormalToRef(vector, transformation, result);
  4225. return result;
  4226. };
  4227. /**
  4228. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4229. * This methods computes transformed normalized direction vectors only.
  4230. */
  4231. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4232. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4233. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4234. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4235. result.x = x;
  4236. result.y = y;
  4237. result.z = z;
  4238. result.w = vector.w;
  4239. };
  4240. /**
  4241. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4242. * This methods computes transformed normalized direction vectors only.
  4243. */
  4244. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4245. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4246. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4247. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4248. result.w = w;
  4249. };
  4250. return Vector4;
  4251. }());
  4252. BABYLON.Vector4 = Vector4;
  4253. var Size = /** @class */ (function () {
  4254. /**
  4255. * Creates a Size object from the given width and height (floats).
  4256. */
  4257. function Size(width, height) {
  4258. this.width = width;
  4259. this.height = height;
  4260. }
  4261. // Returns a string with the Size width and height.
  4262. Size.prototype.toString = function () {
  4263. return "{W: " + this.width + ", H: " + this.height + "}";
  4264. };
  4265. /**
  4266. * Returns the string "Size"
  4267. */
  4268. Size.prototype.getClassName = function () {
  4269. return "Size";
  4270. };
  4271. /**
  4272. * Returns the Size hash code.
  4273. */
  4274. Size.prototype.getHashCode = function () {
  4275. var hash = this.width || 0;
  4276. hash = (hash * 397) ^ (this.height || 0);
  4277. return hash;
  4278. };
  4279. /**
  4280. * Updates the current size from the given one.
  4281. * Returns the updated Size.
  4282. */
  4283. Size.prototype.copyFrom = function (src) {
  4284. this.width = src.width;
  4285. this.height = src.height;
  4286. };
  4287. /**
  4288. * Updates in place the current Size from the given floats.
  4289. * Returns the updated Size.
  4290. */
  4291. Size.prototype.copyFromFloats = function (width, height) {
  4292. this.width = width;
  4293. this.height = height;
  4294. return this;
  4295. };
  4296. /**
  4297. * Updates in place the current Size from the given floats.
  4298. * Returns the updated Size.
  4299. */
  4300. Size.prototype.set = function (width, height) {
  4301. return this.copyFromFloats(width, height);
  4302. };
  4303. /**
  4304. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4305. */
  4306. Size.prototype.multiplyByFloats = function (w, h) {
  4307. return new Size(this.width * w, this.height * h);
  4308. };
  4309. /**
  4310. * Returns a new Size copied from the given one.
  4311. */
  4312. Size.prototype.clone = function () {
  4313. return new Size(this.width, this.height);
  4314. };
  4315. /**
  4316. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4317. */
  4318. Size.prototype.equals = function (other) {
  4319. if (!other) {
  4320. return false;
  4321. }
  4322. return (this.width === other.width) && (this.height === other.height);
  4323. };
  4324. Object.defineProperty(Size.prototype, "surface", {
  4325. /**
  4326. * Returns the surface of the Size : width * height (float).
  4327. */
  4328. get: function () {
  4329. return this.width * this.height;
  4330. },
  4331. enumerable: true,
  4332. configurable: true
  4333. });
  4334. /**
  4335. * Returns a new Size set to (0.0, 0.0)
  4336. */
  4337. Size.Zero = function () {
  4338. return new Size(0.0, 0.0);
  4339. };
  4340. /**
  4341. * Returns a new Size set as the addition result of the current Size and the given one.
  4342. */
  4343. Size.prototype.add = function (otherSize) {
  4344. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4345. return r;
  4346. };
  4347. /**
  4348. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4349. */
  4350. Size.prototype.subtract = function (otherSize) {
  4351. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4352. return r;
  4353. };
  4354. /**
  4355. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4356. */
  4357. Size.Lerp = function (start, end, amount) {
  4358. var w = start.width + ((end.width - start.width) * amount);
  4359. var h = start.height + ((end.height - start.height) * amount);
  4360. return new Size(w, h);
  4361. };
  4362. return Size;
  4363. }());
  4364. BABYLON.Size = Size;
  4365. /**
  4366. * Class used to store quaternion data
  4367. * @see https://en.wikipedia.org/wiki/Quaternion
  4368. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4369. */
  4370. var Quaternion = /** @class */ (function () {
  4371. /**
  4372. * Creates a new Quaternion from the given floats
  4373. * @param x defines the first component (0 by default)
  4374. * @param y defines the second component (0 by default)
  4375. * @param z defines the third component (0 by default)
  4376. * @param w defines the fourth component (1.0 by default)
  4377. */
  4378. function Quaternion(
  4379. /** defines the first component (0 by default) */
  4380. x,
  4381. /** defines the second component (0 by default) */
  4382. y,
  4383. /** defines the third component (0 by default) */
  4384. z,
  4385. /** defines the fourth component (1.0 by default) */
  4386. w) {
  4387. if (x === void 0) { x = 0.0; }
  4388. if (y === void 0) { y = 0.0; }
  4389. if (z === void 0) { z = 0.0; }
  4390. if (w === void 0) { w = 1.0; }
  4391. this.x = x;
  4392. this.y = y;
  4393. this.z = z;
  4394. this.w = w;
  4395. }
  4396. /**
  4397. * Gets a string representation for the current quaternion
  4398. * @returns a string with the Quaternion coordinates
  4399. */
  4400. Quaternion.prototype.toString = function () {
  4401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4402. };
  4403. /**
  4404. * Gets the class name of the quaternion
  4405. * @returns the string "Quaternion"
  4406. */
  4407. Quaternion.prototype.getClassName = function () {
  4408. return "Quaternion";
  4409. };
  4410. /**
  4411. * Gets a hash code for this quaternion
  4412. * @returns the quaternion hash code
  4413. */
  4414. Quaternion.prototype.getHashCode = function () {
  4415. var hash = this.x || 0;
  4416. hash = (hash * 397) ^ (this.y || 0);
  4417. hash = (hash * 397) ^ (this.z || 0);
  4418. hash = (hash * 397) ^ (this.w || 0);
  4419. return hash;
  4420. };
  4421. /**
  4422. * Copy the quaternion to an array
  4423. * @returns a new array populated with 4 elements from the quaternion coordinates
  4424. */
  4425. Quaternion.prototype.asArray = function () {
  4426. return [this.x, this.y, this.z, this.w];
  4427. };
  4428. /**
  4429. * Check if two quaternions are equals
  4430. * @param otherQuaternion defines the second operand
  4431. * @return true if the current quaternion and the given one coordinates are strictly equals
  4432. */
  4433. Quaternion.prototype.equals = function (otherQuaternion) {
  4434. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4435. };
  4436. /**
  4437. * Clone the current quaternion
  4438. * @returns a new quaternion copied from the current one
  4439. */
  4440. Quaternion.prototype.clone = function () {
  4441. return new Quaternion(this.x, this.y, this.z, this.w);
  4442. };
  4443. /**
  4444. * Copy a quaternion to the current one
  4445. * @param other defines the other quaternion
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFrom = function (other) {
  4449. this.x = other.x;
  4450. this.y = other.y;
  4451. this.z = other.z;
  4452. this.w = other.w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion with the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4464. this.x = x;
  4465. this.y = y;
  4466. this.z = z;
  4467. this.w = w;
  4468. return this;
  4469. };
  4470. /**
  4471. * Updates the current quaternion from the given float coordinates
  4472. * @param x defines the x coordinate
  4473. * @param y defines the y coordinate
  4474. * @param z defines the z coordinate
  4475. * @param w defines the w coordinate
  4476. * @returns the updated current quaternion
  4477. */
  4478. Quaternion.prototype.set = function (x, y, z, w) {
  4479. return this.copyFromFloats(x, y, z, w);
  4480. };
  4481. /**
  4482. * Adds two quaternions
  4483. * @param other defines the second operand
  4484. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4485. */
  4486. Quaternion.prototype.add = function (other) {
  4487. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4488. };
  4489. /**
  4490. * Add a quaternion to the current one
  4491. * @param other defines the quaternion to add
  4492. * @returns the current quaternion
  4493. */
  4494. Quaternion.prototype.addInPlace = function (other) {
  4495. this.x += other.x;
  4496. this.y += other.y;
  4497. this.z += other.z;
  4498. this.w += other.w;
  4499. return this;
  4500. };
  4501. /**
  4502. * Subtract two quaternions
  4503. * @param other defines the second operand
  4504. * @returns a new quaternion as the subtraction result of the given one from the current one
  4505. */
  4506. Quaternion.prototype.subtract = function (other) {
  4507. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4508. };
  4509. /**
  4510. * Multiplies the current quaternion by a scale factor
  4511. * @param value defines the scale factor
  4512. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4513. */
  4514. Quaternion.prototype.scale = function (value) {
  4515. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4516. };
  4517. /**
  4518. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4519. * @param scale defines the scale factor
  4520. * @param result defines the Quaternion object where to store the result
  4521. * @returns the unmodified current quaternion
  4522. */
  4523. Quaternion.prototype.scaleToRef = function (scale, result) {
  4524. result.x = this.x * scale;
  4525. result.y = this.y * scale;
  4526. result.z = this.z * scale;
  4527. result.w = this.w * scale;
  4528. return this;
  4529. };
  4530. /**
  4531. * Multiplies in place the current quaternion by a scale factor
  4532. * @param value defines the scale factor
  4533. * @returns the current modified quaternion
  4534. */
  4535. Quaternion.prototype.scaleInPlace = function (value) {
  4536. this.x *= value;
  4537. this.y *= value;
  4538. this.z *= value;
  4539. this.w *= value;
  4540. return this;
  4541. };
  4542. /**
  4543. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4544. * @param scale defines the scale factor
  4545. * @param result defines the Quaternion object where to store the result
  4546. * @returns the unmodified current quaternion
  4547. */
  4548. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4549. result.x += this.x * scale;
  4550. result.y += this.y * scale;
  4551. result.z += this.z * scale;
  4552. result.w += this.w * scale;
  4553. return this;
  4554. };
  4555. /**
  4556. * Multiplies two quaternions
  4557. * @param q1 defines the second operand
  4558. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4559. */
  4560. Quaternion.prototype.multiply = function (q1) {
  4561. var result = new Quaternion(0, 0, 0, 1.0);
  4562. this.multiplyToRef(q1, result);
  4563. return result;
  4564. };
  4565. /**
  4566. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4567. * @param q1 defines the second operand
  4568. * @param result defines the target quaternion
  4569. * @returns the current quaternion
  4570. */
  4571. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4572. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4573. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4574. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4575. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4576. result.copyFromFloats(x, y, z, w);
  4577. return this;
  4578. };
  4579. /**
  4580. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4581. * @param q1 defines the second operand
  4582. * @returns the currentupdated quaternion
  4583. */
  4584. Quaternion.prototype.multiplyInPlace = function (q1) {
  4585. this.multiplyToRef(q1, this);
  4586. return this;
  4587. };
  4588. /**
  4589. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4590. * @param ref defines the target quaternion
  4591. * @returns the current quaternion
  4592. */
  4593. Quaternion.prototype.conjugateToRef = function (ref) {
  4594. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4595. return this;
  4596. };
  4597. /**
  4598. * Conjugates in place (1-q) the current quaternion
  4599. * @returns the current updated quaternion
  4600. */
  4601. Quaternion.prototype.conjugateInPlace = function () {
  4602. this.x *= -1;
  4603. this.y *= -1;
  4604. this.z *= -1;
  4605. return this;
  4606. };
  4607. /**
  4608. * Conjugates in place (1-q) the current quaternion
  4609. * @returns a new quaternion
  4610. */
  4611. Quaternion.prototype.conjugate = function () {
  4612. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4613. return result;
  4614. };
  4615. /**
  4616. * Gets length of current quaternion
  4617. * @returns the quaternion length (float)
  4618. */
  4619. Quaternion.prototype.length = function () {
  4620. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4621. };
  4622. /**
  4623. * Normalize in place the current quaternion
  4624. * @returns the current updated quaternion
  4625. */
  4626. Quaternion.prototype.normalize = function () {
  4627. var length = 1.0 / this.length();
  4628. this.x *= length;
  4629. this.y *= length;
  4630. this.z *= length;
  4631. this.w *= length;
  4632. return this;
  4633. };
  4634. /**
  4635. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4636. * @param order is a reserved parameter and is ignore for now
  4637. * @returns a new Vector3 containing the Euler angles
  4638. */
  4639. Quaternion.prototype.toEulerAngles = function (order) {
  4640. if (order === void 0) { order = "YZX"; }
  4641. var result = Vector3.Zero();
  4642. this.toEulerAnglesToRef(result, order);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4647. * @param result defines the vector which will be filled with the Euler angles
  4648. * @param order is a reserved parameter and is ignore for now
  4649. * @returns the current unchanged quaternion
  4650. */
  4651. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4652. if (order === void 0) { order = "YZX"; }
  4653. var qz = this.z;
  4654. var qx = this.x;
  4655. var qy = this.y;
  4656. var qw = this.w;
  4657. var sqw = qw * qw;
  4658. var sqz = qz * qz;
  4659. var sqx = qx * qx;
  4660. var sqy = qy * qy;
  4661. var zAxisY = qy * qz - qx * qw;
  4662. var limit = .4999999;
  4663. if (zAxisY < -limit) {
  4664. result.y = 2 * Math.atan2(qy, qw);
  4665. result.x = Math.PI / 2;
  4666. result.z = 0;
  4667. }
  4668. else if (zAxisY > limit) {
  4669. result.y = 2 * Math.atan2(qy, qw);
  4670. result.x = -Math.PI / 2;
  4671. result.z = 0;
  4672. }
  4673. else {
  4674. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4675. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4676. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4677. }
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the given rotation matrix with the current quaternion values
  4682. * @param result defines the target matrix
  4683. * @returns the current unchanged quaternion
  4684. */
  4685. Quaternion.prototype.toRotationMatrix = function (result) {
  4686. var xx = this.x * this.x;
  4687. var yy = this.y * this.y;
  4688. var zz = this.z * this.z;
  4689. var xy = this.x * this.y;
  4690. var zw = this.z * this.w;
  4691. var zx = this.z * this.x;
  4692. var yw = this.y * this.w;
  4693. var yz = this.y * this.z;
  4694. var xw = this.x * this.w;
  4695. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4696. result.m[1] = 2.0 * (xy + zw);
  4697. result.m[2] = 2.0 * (zx - yw);
  4698. result.m[3] = 0;
  4699. result.m[4] = 2.0 * (xy - zw);
  4700. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4701. result.m[6] = 2.0 * (yz + xw);
  4702. result.m[7] = 0;
  4703. result.m[8] = 2.0 * (zx + yw);
  4704. result.m[9] = 2.0 * (yz - xw);
  4705. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4706. result.m[11] = 0;
  4707. result.m[12] = 0;
  4708. result.m[13] = 0;
  4709. result.m[14] = 0;
  4710. result.m[15] = 1.0;
  4711. result._markAsUpdated();
  4712. return this;
  4713. };
  4714. /**
  4715. * Updates the current quaternion from the given rotation matrix values
  4716. * @param matrix defines the source matrix
  4717. * @returns the current updated quaternion
  4718. */
  4719. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4720. Quaternion.FromRotationMatrixToRef(matrix, this);
  4721. return this;
  4722. };
  4723. // Statics
  4724. /**
  4725. * Creates a new quaternion from a rotation matrix
  4726. * @param matrix defines the source matrix
  4727. * @returns a new quaternion created from the given rotation matrix values
  4728. */
  4729. Quaternion.FromRotationMatrix = function (matrix) {
  4730. var result = new Quaternion();
  4731. Quaternion.FromRotationMatrixToRef(matrix, result);
  4732. return result;
  4733. };
  4734. /**
  4735. * Updates the given quaternion with the given rotation matrix values
  4736. * @param matrix defines the source matrix
  4737. * @param result defines the target quaternion
  4738. */
  4739. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4740. var data = matrix.m;
  4741. var m11 = data[0], m12 = data[4], m13 = data[8];
  4742. var m21 = data[1], m22 = data[5], m23 = data[9];
  4743. var m31 = data[2], m32 = data[6], m33 = data[10];
  4744. var trace = m11 + m22 + m33;
  4745. var s;
  4746. if (trace > 0) {
  4747. s = 0.5 / Math.sqrt(trace + 1.0);
  4748. result.w = 0.25 / s;
  4749. result.x = (m32 - m23) * s;
  4750. result.y = (m13 - m31) * s;
  4751. result.z = (m21 - m12) * s;
  4752. }
  4753. else if (m11 > m22 && m11 > m33) {
  4754. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4755. result.w = (m32 - m23) / s;
  4756. result.x = 0.25 * s;
  4757. result.y = (m12 + m21) / s;
  4758. result.z = (m13 + m31) / s;
  4759. }
  4760. else if (m22 > m33) {
  4761. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4762. result.w = (m13 - m31) / s;
  4763. result.x = (m12 + m21) / s;
  4764. result.y = 0.25 * s;
  4765. result.z = (m23 + m32) / s;
  4766. }
  4767. else {
  4768. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4769. result.w = (m21 - m12) / s;
  4770. result.x = (m13 + m31) / s;
  4771. result.y = (m23 + m32) / s;
  4772. result.z = 0.25 * s;
  4773. }
  4774. };
  4775. /**
  4776. * Returns the dot product (float) between the quaternions "left" and "right"
  4777. * @param left defines the left operand
  4778. * @param right defines the right operand
  4779. * @returns the dot product
  4780. */
  4781. Quaternion.Dot = function (left, right) {
  4782. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4783. };
  4784. /**
  4785. * Checks if the two quaternions are close to each other
  4786. * @param quat0 defines the first quaternion to check
  4787. * @param quat1 defines the second quaternion to check
  4788. * @returns true if the two quaternions are close to each other
  4789. */
  4790. Quaternion.AreClose = function (quat0, quat1) {
  4791. var dot = Quaternion.Dot(quat0, quat1);
  4792. return dot >= 0;
  4793. };
  4794. /**
  4795. * Creates an empty quaternion
  4796. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4797. */
  4798. Quaternion.Zero = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4800. };
  4801. /**
  4802. * Inverse a given quaternion
  4803. * @param q defines the source quaternion
  4804. * @returns a new quaternion as the inverted current quaternion
  4805. */
  4806. Quaternion.Inverse = function (q) {
  4807. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4808. };
  4809. /**
  4810. * Creates an identity quaternion
  4811. * @returns the identity quaternion
  4812. */
  4813. Quaternion.Identity = function () {
  4814. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4815. };
  4816. /**
  4817. * Gets a boolean indicating if the given quaternion is identity
  4818. * @param quaternion defines the quaternion to check
  4819. * @returns true if the quaternion is identity
  4820. */
  4821. Quaternion.IsIdentity = function (quaternion) {
  4822. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4823. };
  4824. /**
  4825. * Creates a quaternion from a rotation around an axis
  4826. * @param axis defines the axis to use
  4827. * @param angle defines the angle to use
  4828. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4829. */
  4830. Quaternion.RotationAxis = function (axis, angle) {
  4831. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4832. };
  4833. /**
  4834. * Creates a rotation around an axis and stores it into the given quaternion
  4835. * @param axis defines the axis to use
  4836. * @param angle defines the angle to use
  4837. * @param result defines the target quaternion
  4838. * @returns the target quaternion
  4839. */
  4840. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4841. var sin = Math.sin(angle / 2);
  4842. axis.normalize();
  4843. result.w = Math.cos(angle / 2);
  4844. result.x = axis.x * sin;
  4845. result.y = axis.y * sin;
  4846. result.z = axis.z * sin;
  4847. return result;
  4848. };
  4849. /**
  4850. * Creates a new quaternion from data stored into an array
  4851. * @param array defines the data source
  4852. * @param offset defines the offset in the source array where the data starts
  4853. * @returns a new quaternion
  4854. */
  4855. Quaternion.FromArray = function (array, offset) {
  4856. if (!offset) {
  4857. offset = 0;
  4858. }
  4859. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4860. };
  4861. /**
  4862. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4863. * @param yaw defines the rotation around Y axis
  4864. * @param pitch defines the rotation around X axis
  4865. * @param roll defines the rotation around Z axis
  4866. * @returns the new quaternion
  4867. */
  4868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4869. var q = new Quaternion();
  4870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4871. return q;
  4872. };
  4873. /**
  4874. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4875. * @param yaw defines the rotation around Y axis
  4876. * @param pitch defines the rotation around X axis
  4877. * @param roll defines the rotation around Z axis
  4878. * @param result defines the target quaternion
  4879. */
  4880. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4881. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4882. var halfRoll = roll * 0.5;
  4883. var halfPitch = pitch * 0.5;
  4884. var halfYaw = yaw * 0.5;
  4885. var sinRoll = Math.sin(halfRoll);
  4886. var cosRoll = Math.cos(halfRoll);
  4887. var sinPitch = Math.sin(halfPitch);
  4888. var cosPitch = Math.cos(halfPitch);
  4889. var sinYaw = Math.sin(halfYaw);
  4890. var cosYaw = Math.cos(halfYaw);
  4891. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4892. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4893. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4894. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4895. };
  4896. /**
  4897. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4898. * @param alpha defines the rotation around first axis
  4899. * @param beta defines the rotation around second axis
  4900. * @param gamma defines the rotation around third axis
  4901. * @returns the new quaternion
  4902. */
  4903. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4904. var result = new Quaternion();
  4905. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4906. return result;
  4907. };
  4908. /**
  4909. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4910. * @param alpha defines the rotation around first axis
  4911. * @param beta defines the rotation around second axis
  4912. * @param gamma defines the rotation around third axis
  4913. * @param result defines the target quaternion
  4914. */
  4915. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4916. // Produces a quaternion from Euler angles in the z-x-z orientation
  4917. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4918. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4919. var halfBeta = beta * 0.5;
  4920. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4921. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4922. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4923. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4924. };
  4925. /**
  4926. * 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)
  4927. * @param axis1 defines the first axis
  4928. * @param axis2 defines the second axis
  4929. * @param axis3 defines the third axis
  4930. * @returns the new quaternion
  4931. */
  4932. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4933. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4934. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4935. return quat;
  4936. };
  4937. /**
  4938. * 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
  4939. * @param axis1 defines the first axis
  4940. * @param axis2 defines the second axis
  4941. * @param axis3 defines the third axis
  4942. * @param ref defines the target quaternion
  4943. */
  4944. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4945. var rotMat = MathTmp.Matrix[0];
  4946. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4947. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4948. };
  4949. /**
  4950. * Interpolates between two quaternions
  4951. * @param left defines first quaternion
  4952. * @param right defines second quaternion
  4953. * @param amount defines the gradient to use
  4954. * @returns the new interpolated quaternion
  4955. */
  4956. Quaternion.Slerp = function (left, right, amount) {
  4957. var result = Quaternion.Identity();
  4958. Quaternion.SlerpToRef(left, right, amount, result);
  4959. return result;
  4960. };
  4961. /**
  4962. * Interpolates between two quaternions and stores it into a target quaternion
  4963. * @param left defines first quaternion
  4964. * @param right defines second quaternion
  4965. * @param amount defines the gradient to use
  4966. * @param result defines the target quaternion
  4967. */
  4968. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4969. var num2;
  4970. var num3;
  4971. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4972. var flag = false;
  4973. if (num4 < 0) {
  4974. flag = true;
  4975. num4 = -num4;
  4976. }
  4977. if (num4 > 0.999999) {
  4978. num3 = 1 - amount;
  4979. num2 = flag ? -amount : amount;
  4980. }
  4981. else {
  4982. var num5 = Math.acos(num4);
  4983. var num6 = (1.0 / Math.sin(num5));
  4984. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4985. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4986. }
  4987. result.x = (num3 * left.x) + (num2 * right.x);
  4988. result.y = (num3 * left.y) + (num2 * right.y);
  4989. result.z = (num3 * left.z) + (num2 * right.z);
  4990. result.w = (num3 * left.w) + (num2 * right.w);
  4991. };
  4992. /**
  4993. * Interpolate between two quaternions using Hermite interpolation
  4994. * @param value1 defines first quaternion
  4995. * @param tangent1 defines the incoming tangent
  4996. * @param value2 defines second quaternion
  4997. * @param tangent2 defines the outgoing tangent
  4998. * @param amount defines the target quaternion
  4999. * @returns the new interpolated quaternion
  5000. */
  5001. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5002. var squared = amount * amount;
  5003. var cubed = amount * squared;
  5004. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5005. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5006. var part3 = (cubed - (2.0 * squared)) + amount;
  5007. var part4 = cubed - squared;
  5008. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5009. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5010. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5011. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5012. return new Quaternion(x, y, z, w);
  5013. };
  5014. return Quaternion;
  5015. }());
  5016. BABYLON.Quaternion = Quaternion;
  5017. /**
  5018. * Class used to store matrix data (4x4)
  5019. */
  5020. var Matrix = /** @class */ (function () {
  5021. /**
  5022. * Creates an empty matrix (filled with zeros)
  5023. */
  5024. function Matrix() {
  5025. this._isIdentity = false;
  5026. this._isIdentityDirty = true;
  5027. /**
  5028. * Gets or sets the internal data of the matrix
  5029. */
  5030. this.m = new Float32Array(16);
  5031. this._markAsUpdated();
  5032. }
  5033. /** @hidden */
  5034. Matrix.prototype._markAsUpdated = function () {
  5035. this.updateFlag = Matrix._updateFlagSeed++;
  5036. this._isIdentityDirty = true;
  5037. };
  5038. // Properties
  5039. /**
  5040. * Check if the current matrix is indentity
  5041. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5042. * @returns true is the matrix is the identity matrix
  5043. */
  5044. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5045. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5046. if (this._isIdentityDirty) {
  5047. this._isIdentityDirty = false;
  5048. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5049. this._isIdentity = false;
  5050. }
  5051. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5052. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5053. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5054. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5055. this._isIdentity = false;
  5056. }
  5057. else {
  5058. this._isIdentity = true;
  5059. }
  5060. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5061. this._isIdentity = false;
  5062. }
  5063. }
  5064. return this._isIdentity;
  5065. };
  5066. /**
  5067. * Gets the determinant of the matrix
  5068. * @returns the matrix determinant
  5069. */
  5070. Matrix.prototype.determinant = function () {
  5071. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5072. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5073. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5074. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5075. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5076. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5077. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5078. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5079. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5080. };
  5081. // Methods
  5082. /**
  5083. * Returns the matrix as a Float32Array
  5084. * @returns the matrix underlying array
  5085. */
  5086. Matrix.prototype.toArray = function () {
  5087. return this.m;
  5088. };
  5089. /**
  5090. * Returns the matrix as a Float32Array
  5091. * @returns the matrix underlying array.
  5092. */
  5093. Matrix.prototype.asArray = function () {
  5094. return this.toArray();
  5095. };
  5096. /**
  5097. * Inverts the current matrix in place
  5098. * @returns the current inverted matrix
  5099. */
  5100. Matrix.prototype.invert = function () {
  5101. this.invertToRef(this);
  5102. return this;
  5103. };
  5104. /**
  5105. * Sets all the matrix elements to zero
  5106. * @returns the current matrix
  5107. */
  5108. Matrix.prototype.reset = function () {
  5109. for (var index = 0; index < 16; index++) {
  5110. this.m[index] = 0.0;
  5111. }
  5112. this._markAsUpdated();
  5113. return this;
  5114. };
  5115. /**
  5116. * Adds the current matrix with a second one
  5117. * @param other defines the matrix to add
  5118. * @returns a new matrix as the addition of the current matrix and the given one
  5119. */
  5120. Matrix.prototype.add = function (other) {
  5121. var result = new Matrix();
  5122. this.addToRef(other, result);
  5123. return result;
  5124. };
  5125. /**
  5126. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5127. * @param other defines the matrix to add
  5128. * @param result defines the target matrix
  5129. * @returns the current matrix
  5130. */
  5131. Matrix.prototype.addToRef = function (other, result) {
  5132. for (var index = 0; index < 16; index++) {
  5133. result.m[index] = this.m[index] + other.m[index];
  5134. }
  5135. result._markAsUpdated();
  5136. return this;
  5137. };
  5138. /**
  5139. * Adds in place the given matrix to the current matrix
  5140. * @param other defines the second operand
  5141. * @returns the current updated matrix
  5142. */
  5143. Matrix.prototype.addToSelf = function (other) {
  5144. for (var index = 0; index < 16; index++) {
  5145. this.m[index] += other.m[index];
  5146. }
  5147. this._markAsUpdated();
  5148. return this;
  5149. };
  5150. /**
  5151. * Sets the given matrix to the current inverted Matrix
  5152. * @param other defines the target matrix
  5153. * @returns the unmodified current matrix
  5154. */
  5155. Matrix.prototype.invertToRef = function (other) {
  5156. var l1 = this.m[0];
  5157. var l2 = this.m[1];
  5158. var l3 = this.m[2];
  5159. var l4 = this.m[3];
  5160. var l5 = this.m[4];
  5161. var l6 = this.m[5];
  5162. var l7 = this.m[6];
  5163. var l8 = this.m[7];
  5164. var l9 = this.m[8];
  5165. var l10 = this.m[9];
  5166. var l11 = this.m[10];
  5167. var l12 = this.m[11];
  5168. var l13 = this.m[12];
  5169. var l14 = this.m[13];
  5170. var l15 = this.m[14];
  5171. var l16 = this.m[15];
  5172. var l17 = (l11 * l16) - (l12 * l15);
  5173. var l18 = (l10 * l16) - (l12 * l14);
  5174. var l19 = (l10 * l15) - (l11 * l14);
  5175. var l20 = (l9 * l16) - (l12 * l13);
  5176. var l21 = (l9 * l15) - (l11 * l13);
  5177. var l22 = (l9 * l14) - (l10 * l13);
  5178. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5179. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5180. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5181. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5182. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5183. var l28 = (l7 * l16) - (l8 * l15);
  5184. var l29 = (l6 * l16) - (l8 * l14);
  5185. var l30 = (l6 * l15) - (l7 * l14);
  5186. var l31 = (l5 * l16) - (l8 * l13);
  5187. var l32 = (l5 * l15) - (l7 * l13);
  5188. var l33 = (l5 * l14) - (l6 * l13);
  5189. var l34 = (l7 * l12) - (l8 * l11);
  5190. var l35 = (l6 * l12) - (l8 * l10);
  5191. var l36 = (l6 * l11) - (l7 * l10);
  5192. var l37 = (l5 * l12) - (l8 * l9);
  5193. var l38 = (l5 * l11) - (l7 * l9);
  5194. var l39 = (l5 * l10) - (l6 * l9);
  5195. other.m[0] = l23 * l27;
  5196. other.m[4] = l24 * l27;
  5197. other.m[8] = l25 * l27;
  5198. other.m[12] = l26 * l27;
  5199. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5200. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5201. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5202. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5203. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5204. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5205. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5206. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5207. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5208. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5209. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5210. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5211. other._markAsUpdated();
  5212. return this;
  5213. };
  5214. /**
  5215. * Inserts the translation vector (using 3 floats) in the current matrix
  5216. * @param x defines the 1st component of the translation
  5217. * @param y defines the 2nd component of the translation
  5218. * @param z defines the 3rd component of the translation
  5219. * @returns the current updated matrix
  5220. */
  5221. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5222. this.m[12] = x;
  5223. this.m[13] = y;
  5224. this.m[14] = z;
  5225. this._markAsUpdated();
  5226. return this;
  5227. };
  5228. /**
  5229. * Inserts the translation vector in the current matrix
  5230. * @param vector3 defines the translation to insert
  5231. * @returns the current updated matrix
  5232. */
  5233. Matrix.prototype.setTranslation = function (vector3) {
  5234. this.m[12] = vector3.x;
  5235. this.m[13] = vector3.y;
  5236. this.m[14] = vector3.z;
  5237. this._markAsUpdated();
  5238. return this;
  5239. };
  5240. /**
  5241. * Gets the translation value of the current matrix
  5242. * @returns a new Vector3 as the extracted translation from the matrix
  5243. */
  5244. Matrix.prototype.getTranslation = function () {
  5245. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5246. };
  5247. /**
  5248. * Fill a Vector3 with the extracted translation from the matrix
  5249. * @param result defines the Vector3 where to store the translation
  5250. * @returns the current matrix
  5251. */
  5252. Matrix.prototype.getTranslationToRef = function (result) {
  5253. result.x = this.m[12];
  5254. result.y = this.m[13];
  5255. result.z = this.m[14];
  5256. return this;
  5257. };
  5258. /**
  5259. * Remove rotation and scaling part from the matrix
  5260. * @returns the updated matrix
  5261. */
  5262. Matrix.prototype.removeRotationAndScaling = function () {
  5263. this.setRowFromFloats(0, 1, 0, 0, 0);
  5264. this.setRowFromFloats(1, 0, 1, 0, 0);
  5265. this.setRowFromFloats(2, 0, 0, 1, 0);
  5266. return this;
  5267. };
  5268. /**
  5269. * Multiply two matrices
  5270. * @param other defines the second operand
  5271. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5272. */
  5273. Matrix.prototype.multiply = function (other) {
  5274. var result = new Matrix();
  5275. this.multiplyToRef(other, result);
  5276. return result;
  5277. };
  5278. /**
  5279. * Copy the current matrix from the given one
  5280. * @param other defines the source matrix
  5281. * @returns the current updated matrix
  5282. */
  5283. Matrix.prototype.copyFrom = function (other) {
  5284. for (var index = 0; index < 16; index++) {
  5285. this.m[index] = other.m[index];
  5286. }
  5287. this._markAsUpdated();
  5288. return this;
  5289. };
  5290. /**
  5291. * Populates the given array from the starting index with the current matrix values
  5292. * @param array defines the target array
  5293. * @param offset defines the offset in the target array where to start storing values
  5294. * @returns the current matrix
  5295. */
  5296. Matrix.prototype.copyToArray = function (array, offset) {
  5297. if (offset === void 0) { offset = 0; }
  5298. for (var index = 0; index < 16; index++) {
  5299. array[offset + index] = this.m[index];
  5300. }
  5301. return this;
  5302. };
  5303. /**
  5304. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5305. * @param other defines the second operand
  5306. * @param result defines the matrix where to store the multiplication
  5307. * @returns the current matrix
  5308. */
  5309. Matrix.prototype.multiplyToRef = function (other, result) {
  5310. this.multiplyToArray(other, result.m, 0);
  5311. result._markAsUpdated();
  5312. return this;
  5313. };
  5314. /**
  5315. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5316. * @param other defines the second operand
  5317. * @param result defines the array where to store the multiplication
  5318. * @param offset defines the offset in the target array where to start storing values
  5319. * @returns the current matrix
  5320. */
  5321. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5322. var tm0 = this.m[0];
  5323. var tm1 = this.m[1];
  5324. var tm2 = this.m[2];
  5325. var tm3 = this.m[3];
  5326. var tm4 = this.m[4];
  5327. var tm5 = this.m[5];
  5328. var tm6 = this.m[6];
  5329. var tm7 = this.m[7];
  5330. var tm8 = this.m[8];
  5331. var tm9 = this.m[9];
  5332. var tm10 = this.m[10];
  5333. var tm11 = this.m[11];
  5334. var tm12 = this.m[12];
  5335. var tm13 = this.m[13];
  5336. var tm14 = this.m[14];
  5337. var tm15 = this.m[15];
  5338. var om0 = other.m[0];
  5339. var om1 = other.m[1];
  5340. var om2 = other.m[2];
  5341. var om3 = other.m[3];
  5342. var om4 = other.m[4];
  5343. var om5 = other.m[5];
  5344. var om6 = other.m[6];
  5345. var om7 = other.m[7];
  5346. var om8 = other.m[8];
  5347. var om9 = other.m[9];
  5348. var om10 = other.m[10];
  5349. var om11 = other.m[11];
  5350. var om12 = other.m[12];
  5351. var om13 = other.m[13];
  5352. var om14 = other.m[14];
  5353. var om15 = other.m[15];
  5354. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5355. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5356. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5357. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5358. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5359. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5360. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5361. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5362. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5363. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5364. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5365. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5366. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5367. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5368. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5369. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5370. return this;
  5371. };
  5372. /**
  5373. * Check equality between this matrix and a second one
  5374. * @param value defines the second matrix to compare
  5375. * @returns true is the current matrix and the given one values are strictly equal
  5376. */
  5377. Matrix.prototype.equals = function (value) {
  5378. return value &&
  5379. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5380. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5381. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5382. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5383. };
  5384. /**
  5385. * Clone the current matrix
  5386. * @returns a new matrix from the current matrix
  5387. */
  5388. Matrix.prototype.clone = function () {
  5389. 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]);
  5390. };
  5391. /**
  5392. * Returns the name of the current matrix class
  5393. * @returns the string "Matrix"
  5394. */
  5395. Matrix.prototype.getClassName = function () {
  5396. return "Matrix";
  5397. };
  5398. /**
  5399. * Gets the hash code of the current matrix
  5400. * @returns the hash code
  5401. */
  5402. Matrix.prototype.getHashCode = function () {
  5403. var hash = this.m[0] || 0;
  5404. for (var i = 1; i < 16; i++) {
  5405. hash = (hash * 397) ^ (this.m[i] || 0);
  5406. }
  5407. return hash;
  5408. };
  5409. /**
  5410. * Decomposes the current Matrix into a translation, rotation and scaling components
  5411. * @param scale defines the scale vector3 given as a reference to update
  5412. * @param rotation defines the rotation quaternion given as a reference to update
  5413. * @param translation defines the translation vector3 given as a reference to update
  5414. * @returns true if operation was successful
  5415. */
  5416. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5417. if (translation) {
  5418. translation.x = this.m[12];
  5419. translation.y = this.m[13];
  5420. translation.z = this.m[14];
  5421. }
  5422. scale = scale || MathTmp.Vector3[0];
  5423. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5424. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5425. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5426. if (this.determinant() <= 0) {
  5427. scale.y *= -1;
  5428. }
  5429. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5430. if (rotation) {
  5431. rotation.x = 0;
  5432. rotation.y = 0;
  5433. rotation.z = 0;
  5434. rotation.w = 1;
  5435. }
  5436. return false;
  5437. }
  5438. if (rotation) {
  5439. 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]);
  5440. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5441. }
  5442. return true;
  5443. };
  5444. /**
  5445. * Gets specific row of the matrix
  5446. * @param index defines the number of the row to get
  5447. * @returns the index-th row of the current matrix as a new Vector4
  5448. */
  5449. Matrix.prototype.getRow = function (index) {
  5450. if (index < 0 || index > 3) {
  5451. return null;
  5452. }
  5453. var i = index * 4;
  5454. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5455. };
  5456. /**
  5457. * Sets the index-th row of the current matrix to the vector4 values
  5458. * @param index defines the number of the row to set
  5459. * @param row defines the target vector4
  5460. * @returns the updated current matrix
  5461. */
  5462. Matrix.prototype.setRow = function (index, row) {
  5463. if (index < 0 || index > 3) {
  5464. return this;
  5465. }
  5466. var i = index * 4;
  5467. this.m[i + 0] = row.x;
  5468. this.m[i + 1] = row.y;
  5469. this.m[i + 2] = row.z;
  5470. this.m[i + 3] = row.w;
  5471. this._markAsUpdated();
  5472. return this;
  5473. };
  5474. /**
  5475. * Compute the transpose of the matrix
  5476. * @returns the new transposed matrix
  5477. */
  5478. Matrix.prototype.transpose = function () {
  5479. return Matrix.Transpose(this);
  5480. };
  5481. /**
  5482. * Compute the transpose of the matrix and store it in a given matrix
  5483. * @param result defines the target matrix
  5484. * @returns the current matrix
  5485. */
  5486. Matrix.prototype.transposeToRef = function (result) {
  5487. Matrix.TransposeToRef(this, result);
  5488. return this;
  5489. };
  5490. /**
  5491. * Sets the index-th row of the current matrix with the given 4 x float values
  5492. * @param index defines the row index
  5493. * @param x defines the x component to set
  5494. * @param y defines the y component to set
  5495. * @param z defines the z component to set
  5496. * @param w defines the w component to set
  5497. * @returns the updated current matrix
  5498. */
  5499. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5500. if (index < 0 || index > 3) {
  5501. return this;
  5502. }
  5503. var i = index * 4;
  5504. this.m[i + 0] = x;
  5505. this.m[i + 1] = y;
  5506. this.m[i + 2] = z;
  5507. this.m[i + 3] = w;
  5508. this._markAsUpdated();
  5509. return this;
  5510. };
  5511. /**
  5512. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5513. * @param scale defines the scale factor
  5514. * @returns a new matrix
  5515. */
  5516. Matrix.prototype.scale = function (scale) {
  5517. var result = new Matrix();
  5518. this.scaleToRef(scale, result);
  5519. return result;
  5520. };
  5521. /**
  5522. * Scale the current matrix values by a factor to a given result matrix
  5523. * @param scale defines the scale factor
  5524. * @param result defines the matrix to store the result
  5525. * @returns the current matrix
  5526. */
  5527. Matrix.prototype.scaleToRef = function (scale, result) {
  5528. for (var index = 0; index < 16; index++) {
  5529. result.m[index] = this.m[index] * scale;
  5530. }
  5531. result._markAsUpdated();
  5532. return this;
  5533. };
  5534. /**
  5535. * Scale the current matrix values by a factor and add the result to a given matrix
  5536. * @param scale defines the scale factor
  5537. * @param result defines the Matrix to store the result
  5538. * @returns the current matrix
  5539. */
  5540. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5541. for (var index = 0; index < 16; index++) {
  5542. result.m[index] += this.m[index] * scale;
  5543. }
  5544. result._markAsUpdated();
  5545. return this;
  5546. };
  5547. /**
  5548. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5549. * @param ref matrix to store the result
  5550. */
  5551. Matrix.prototype.toNormalMatrix = function (ref) {
  5552. this.invertToRef(ref);
  5553. ref.transpose();
  5554. var m = ref.m;
  5555. 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);
  5556. };
  5557. /**
  5558. * Gets only rotation part of the current matrix
  5559. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5560. */
  5561. Matrix.prototype.getRotationMatrix = function () {
  5562. var result = Matrix.Identity();
  5563. this.getRotationMatrixToRef(result);
  5564. return result;
  5565. };
  5566. /**
  5567. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5568. * @param result defines the target matrix to store data to
  5569. * @returns the current matrix
  5570. */
  5571. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5572. var m = this.m;
  5573. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5574. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5575. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5576. if (this.determinant() <= 0) {
  5577. sy *= -1;
  5578. }
  5579. if (sx === 0 || sy === 0 || sz === 0) {
  5580. Matrix.IdentityToRef(result);
  5581. }
  5582. else {
  5583. 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);
  5584. }
  5585. return this;
  5586. };
  5587. // Statics
  5588. /**
  5589. * Creates a matrix from an array
  5590. * @param array defines the source array
  5591. * @param offset defines an offset in the source array
  5592. * @returns a new Matrix set from the starting index of the given array
  5593. */
  5594. Matrix.FromArray = function (array, offset) {
  5595. var result = new Matrix();
  5596. if (!offset) {
  5597. offset = 0;
  5598. }
  5599. Matrix.FromArrayToRef(array, offset, result);
  5600. return result;
  5601. };
  5602. /**
  5603. * Copy the content of an array into a given matrix
  5604. * @param array defines the source array
  5605. * @param offset defines an offset in the source array
  5606. * @param result defines the target matrix
  5607. */
  5608. Matrix.FromArrayToRef = function (array, offset, result) {
  5609. for (var index = 0; index < 16; index++) {
  5610. result.m[index] = array[index + offset];
  5611. }
  5612. result._markAsUpdated();
  5613. };
  5614. /**
  5615. * Stores an array into a matrix after having multiplied each component by a given factor
  5616. * @param array defines the source array
  5617. * @param offset defines the offset in the source array
  5618. * @param scale defines the scaling factor
  5619. * @param result defines the target matrix
  5620. */
  5621. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] = array[index + offset] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. };
  5627. /**
  5628. * Stores a list of values (16) inside a given matrix
  5629. * @param initialM11 defines 1st value of 1st row
  5630. * @param initialM12 defines 2nd value of 1st row
  5631. * @param initialM13 defines 3rd value of 1st row
  5632. * @param initialM14 defines 4th value of 1st row
  5633. * @param initialM21 defines 1st value of 2nd row
  5634. * @param initialM22 defines 2nd value of 2nd row
  5635. * @param initialM23 defines 3rd value of 2nd row
  5636. * @param initialM24 defines 4th value of 2nd row
  5637. * @param initialM31 defines 1st value of 3rd row
  5638. * @param initialM32 defines 2nd value of 3rd row
  5639. * @param initialM33 defines 3rd value of 3rd row
  5640. * @param initialM34 defines 4th value of 3rd row
  5641. * @param initialM41 defines 1st value of 4th row
  5642. * @param initialM42 defines 2nd value of 4th row
  5643. * @param initialM43 defines 3rd value of 4th row
  5644. * @param initialM44 defines 4th value of 4th row
  5645. * @param result defines the target matrix
  5646. */
  5647. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5648. result.m[0] = initialM11;
  5649. result.m[1] = initialM12;
  5650. result.m[2] = initialM13;
  5651. result.m[3] = initialM14;
  5652. result.m[4] = initialM21;
  5653. result.m[5] = initialM22;
  5654. result.m[6] = initialM23;
  5655. result.m[7] = initialM24;
  5656. result.m[8] = initialM31;
  5657. result.m[9] = initialM32;
  5658. result.m[10] = initialM33;
  5659. result.m[11] = initialM34;
  5660. result.m[12] = initialM41;
  5661. result.m[13] = initialM42;
  5662. result.m[14] = initialM43;
  5663. result.m[15] = initialM44;
  5664. result._markAsUpdated();
  5665. };
  5666. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5667. /**
  5668. * Gets an identity matrix that must not be updated
  5669. */
  5670. get: function () {
  5671. return Matrix._identityReadOnly;
  5672. },
  5673. enumerable: true,
  5674. configurable: true
  5675. });
  5676. /**
  5677. * Creates new matrix from a list of values (16)
  5678. * @param initialM11 defines 1st value of 1st row
  5679. * @param initialM12 defines 2nd value of 1st row
  5680. * @param initialM13 defines 3rd value of 1st row
  5681. * @param initialM14 defines 4th value of 1st row
  5682. * @param initialM21 defines 1st value of 2nd row
  5683. * @param initialM22 defines 2nd value of 2nd row
  5684. * @param initialM23 defines 3rd value of 2nd row
  5685. * @param initialM24 defines 4th value of 2nd row
  5686. * @param initialM31 defines 1st value of 3rd row
  5687. * @param initialM32 defines 2nd value of 3rd row
  5688. * @param initialM33 defines 3rd value of 3rd row
  5689. * @param initialM34 defines 4th value of 3rd row
  5690. * @param initialM41 defines 1st value of 4th row
  5691. * @param initialM42 defines 2nd value of 4th row
  5692. * @param initialM43 defines 3rd value of 4th row
  5693. * @param initialM44 defines 4th value of 4th row
  5694. * @returns the new matrix
  5695. */
  5696. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5697. var result = new Matrix();
  5698. result.m[0] = initialM11;
  5699. result.m[1] = initialM12;
  5700. result.m[2] = initialM13;
  5701. result.m[3] = initialM14;
  5702. result.m[4] = initialM21;
  5703. result.m[5] = initialM22;
  5704. result.m[6] = initialM23;
  5705. result.m[7] = initialM24;
  5706. result.m[8] = initialM31;
  5707. result.m[9] = initialM32;
  5708. result.m[10] = initialM33;
  5709. result.m[11] = initialM34;
  5710. result.m[12] = initialM41;
  5711. result.m[13] = initialM42;
  5712. result.m[14] = initialM43;
  5713. result.m[15] = initialM44;
  5714. return result;
  5715. };
  5716. /**
  5717. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5718. * @param scale defines the scale vector3
  5719. * @param rotation defines the rotation quaternion
  5720. * @param translation defines the translation vector3
  5721. * @returns a new matrix
  5722. */
  5723. Matrix.Compose = function (scale, rotation, translation) {
  5724. var result = Matrix.Identity();
  5725. Matrix.ComposeToRef(scale, rotation, translation, result);
  5726. return result;
  5727. };
  5728. /**
  5729. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5730. * @param scale defines the scale vector3
  5731. * @param rotation defines the rotation quaternion
  5732. * @param translation defines the translation vector3
  5733. * @param result defines the target matrix
  5734. */
  5735. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5736. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5737. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5738. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5739. result.setTranslation(translation);
  5740. };
  5741. /**
  5742. * Creates a new identity matrix
  5743. * @returns a new identity matrix
  5744. */
  5745. Matrix.Identity = function () {
  5746. 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);
  5747. };
  5748. /**
  5749. * Creates a new identity matrix and stores the result in a given matrix
  5750. * @param result defines the target matrix
  5751. */
  5752. Matrix.IdentityToRef = function (result) {
  5753. 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);
  5754. };
  5755. /**
  5756. * Creates a new zero matrix
  5757. * @returns a new zero matrix
  5758. */
  5759. Matrix.Zero = function () {
  5760. 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);
  5761. };
  5762. /**
  5763. * Creates a new rotation matrix for "angle" radians around the X axis
  5764. * @param angle defines the angle (in radians) to use
  5765. * @return the new matrix
  5766. */
  5767. Matrix.RotationX = function (angle) {
  5768. var result = new Matrix();
  5769. Matrix.RotationXToRef(angle, result);
  5770. return result;
  5771. };
  5772. /**
  5773. * Creates a new matrix as the invert of a given matrix
  5774. * @param source defines the source matrix
  5775. * @returns the new matrix
  5776. */
  5777. Matrix.Invert = function (source) {
  5778. var result = new Matrix();
  5779. source.invertToRef(result);
  5780. return result;
  5781. };
  5782. /**
  5783. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5784. * @param angle defines the angle (in radians) to use
  5785. * @param result defines the target matrix
  5786. */
  5787. Matrix.RotationXToRef = function (angle, result) {
  5788. var s = Math.sin(angle);
  5789. var c = Math.cos(angle);
  5790. result.m[0] = 1.0;
  5791. result.m[15] = 1.0;
  5792. result.m[5] = c;
  5793. result.m[10] = c;
  5794. result.m[9] = -s;
  5795. result.m[6] = s;
  5796. result.m[1] = 0.0;
  5797. result.m[2] = 0.0;
  5798. result.m[3] = 0.0;
  5799. result.m[4] = 0.0;
  5800. result.m[7] = 0.0;
  5801. result.m[8] = 0.0;
  5802. result.m[11] = 0.0;
  5803. result.m[12] = 0.0;
  5804. result.m[13] = 0.0;
  5805. result.m[14] = 0.0;
  5806. result._markAsUpdated();
  5807. };
  5808. /**
  5809. * Creates a new rotation matrix for "angle" radians around the Y axis
  5810. * @param angle defines the angle (in radians) to use
  5811. * @return the new matrix
  5812. */
  5813. Matrix.RotationY = function (angle) {
  5814. var result = new Matrix();
  5815. Matrix.RotationYToRef(angle, result);
  5816. return result;
  5817. };
  5818. /**
  5819. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5820. * @param angle defines the angle (in radians) to use
  5821. * @param result defines the target matrix
  5822. */
  5823. Matrix.RotationYToRef = function (angle, result) {
  5824. var s = Math.sin(angle);
  5825. var c = Math.cos(angle);
  5826. result.m[5] = 1.0;
  5827. result.m[15] = 1.0;
  5828. result.m[0] = c;
  5829. result.m[2] = -s;
  5830. result.m[8] = s;
  5831. result.m[10] = c;
  5832. result.m[1] = 0.0;
  5833. result.m[3] = 0.0;
  5834. result.m[4] = 0.0;
  5835. result.m[6] = 0.0;
  5836. result.m[7] = 0.0;
  5837. result.m[9] = 0.0;
  5838. result.m[11] = 0.0;
  5839. result.m[12] = 0.0;
  5840. result.m[13] = 0.0;
  5841. result.m[14] = 0.0;
  5842. result._markAsUpdated();
  5843. };
  5844. /**
  5845. * Creates a new rotation matrix for "angle" radians around the Z axis
  5846. * @param angle defines the angle (in radians) to use
  5847. * @return the new matrix
  5848. */
  5849. Matrix.RotationZ = function (angle) {
  5850. var result = new Matrix();
  5851. Matrix.RotationZToRef(angle, result);
  5852. return result;
  5853. };
  5854. /**
  5855. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5856. * @param angle defines the angle (in radians) to use
  5857. * @param result defines the target matrix
  5858. */
  5859. Matrix.RotationZToRef = function (angle, result) {
  5860. var s = Math.sin(angle);
  5861. var c = Math.cos(angle);
  5862. result.m[10] = 1.0;
  5863. result.m[15] = 1.0;
  5864. result.m[0] = c;
  5865. result.m[1] = s;
  5866. result.m[4] = -s;
  5867. result.m[5] = c;
  5868. result.m[2] = 0.0;
  5869. result.m[3] = 0.0;
  5870. result.m[6] = 0.0;
  5871. result.m[7] = 0.0;
  5872. result.m[8] = 0.0;
  5873. result.m[9] = 0.0;
  5874. result.m[11] = 0.0;
  5875. result.m[12] = 0.0;
  5876. result.m[13] = 0.0;
  5877. result.m[14] = 0.0;
  5878. result._markAsUpdated();
  5879. };
  5880. /**
  5881. * Creates a new rotation matrix for "angle" radians around the given axis
  5882. * @param axis defines the axis to use
  5883. * @param angle defines the angle (in radians) to use
  5884. * @return the new matrix
  5885. */
  5886. Matrix.RotationAxis = function (axis, angle) {
  5887. var result = Matrix.Zero();
  5888. Matrix.RotationAxisToRef(axis, angle, result);
  5889. return result;
  5890. };
  5891. /**
  5892. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5893. * @param axis defines the axis to use
  5894. * @param angle defines the angle (in radians) to use
  5895. * @param result defines the target matrix
  5896. */
  5897. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5898. var s = Math.sin(-angle);
  5899. var c = Math.cos(-angle);
  5900. var c1 = 1 - c;
  5901. axis.normalize();
  5902. result.m[0] = (axis.x * axis.x) * c1 + c;
  5903. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5904. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5905. result.m[3] = 0.0;
  5906. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5907. result.m[5] = (axis.y * axis.y) * c1 + c;
  5908. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5909. result.m[7] = 0.0;
  5910. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5911. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5912. result.m[10] = (axis.z * axis.z) * c1 + c;
  5913. result.m[11] = 0.0;
  5914. result.m[15] = 1.0;
  5915. result._markAsUpdated();
  5916. };
  5917. /**
  5918. * Creates a rotation matrix
  5919. * @param yaw defines the yaw angle in radians (Y axis)
  5920. * @param pitch defines the pitch angle in radians (X axis)
  5921. * @param roll defines the roll angle in radians (X axis)
  5922. * @returns the new rotation matrix
  5923. */
  5924. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5925. var result = new Matrix();
  5926. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5927. return result;
  5928. };
  5929. /**
  5930. * Creates a rotation matrix and stores it in a given matrix
  5931. * @param yaw defines the yaw angle in radians (Y axis)
  5932. * @param pitch defines the pitch angle in radians (X axis)
  5933. * @param roll defines the roll angle in radians (X axis)
  5934. * @param result defines the target matrix
  5935. */
  5936. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5937. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5938. this._tempQuaternion.toRotationMatrix(result);
  5939. };
  5940. /**
  5941. * Creates a scaling matrix
  5942. * @param x defines the scale factor on X axis
  5943. * @param y defines the scale factor on Y axis
  5944. * @param z defines the scale factor on Z axis
  5945. * @returns the new matrix
  5946. */
  5947. Matrix.Scaling = function (x, y, z) {
  5948. var result = Matrix.Zero();
  5949. Matrix.ScalingToRef(x, y, z, result);
  5950. return result;
  5951. };
  5952. /**
  5953. * Creates a scaling matrix and stores it in a given matrix
  5954. * @param x defines the scale factor on X axis
  5955. * @param y defines the scale factor on Y axis
  5956. * @param z defines the scale factor on Z axis
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.ScalingToRef = function (x, y, z, result) {
  5960. result.m[0] = x;
  5961. result.m[1] = 0.0;
  5962. result.m[2] = 0.0;
  5963. result.m[3] = 0.0;
  5964. result.m[4] = 0.0;
  5965. result.m[5] = y;
  5966. result.m[6] = 0.0;
  5967. result.m[7] = 0.0;
  5968. result.m[8] = 0.0;
  5969. result.m[9] = 0.0;
  5970. result.m[10] = z;
  5971. result.m[11] = 0.0;
  5972. result.m[12] = 0.0;
  5973. result.m[13] = 0.0;
  5974. result.m[14] = 0.0;
  5975. result.m[15] = 1.0;
  5976. result._markAsUpdated();
  5977. };
  5978. /**
  5979. * Creates a translation matrix
  5980. * @param x defines the translation on X axis
  5981. * @param y defines the translation on Y axis
  5982. * @param z defines the translationon Z axis
  5983. * @returns the new matrix
  5984. */
  5985. Matrix.Translation = function (x, y, z) {
  5986. var result = Matrix.Identity();
  5987. Matrix.TranslationToRef(x, y, z, result);
  5988. return result;
  5989. };
  5990. /**
  5991. * Creates a translation matrix and stores it in a given matrix
  5992. * @param x defines the translation on X axis
  5993. * @param y defines the translation on Y axis
  5994. * @param z defines the translationon Z axis
  5995. * @param result defines the target matrix
  5996. */
  5997. Matrix.TranslationToRef = function (x, y, z, result) {
  5998. 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);
  5999. };
  6000. /**
  6001. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6002. * @param startValue defines the start value
  6003. * @param endValue defines the end value
  6004. * @param gradient defines the gradient factor
  6005. * @returns the new matrix
  6006. */
  6007. Matrix.Lerp = function (startValue, endValue, gradient) {
  6008. var result = Matrix.Zero();
  6009. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6010. return result;
  6011. };
  6012. /**
  6013. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6014. * @param startValue defines the start value
  6015. * @param endValue defines the end value
  6016. * @param gradient defines the gradient factor
  6017. * @param result defines the Matrix object where to store data
  6018. */
  6019. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6020. for (var index = 0; index < 16; index++) {
  6021. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6022. }
  6023. result._markAsUpdated();
  6024. };
  6025. /**
  6026. * Builds a new matrix whose values are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @returns the new matrix
  6034. */
  6035. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6036. var result = Matrix.Zero();
  6037. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6038. return result;
  6039. };
  6040. /**
  6041. * Update a matrix to values which are computed by:
  6042. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6043. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6044. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6045. * @param startValue defines the first matrix
  6046. * @param endValue defines the second matrix
  6047. * @param gradient defines the gradient between the two matrices
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6051. var startScale = MathTmp.Vector3[0];
  6052. var startRotation = MathTmp.Quaternion[0];
  6053. var startTranslation = MathTmp.Vector3[1];
  6054. startValue.decompose(startScale, startRotation, startTranslation);
  6055. var endScale = MathTmp.Vector3[2];
  6056. var endRotation = MathTmp.Quaternion[1];
  6057. var endTranslation = MathTmp.Vector3[3];
  6058. endValue.decompose(endScale, endRotation, endTranslation);
  6059. var resultScale = MathTmp.Vector3[4];
  6060. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6061. var resultRotation = MathTmp.Quaternion[2];
  6062. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6063. var resultTranslation = MathTmp.Vector3[5];
  6064. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6065. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6066. };
  6067. /**
  6068. * 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"
  6069. * This function works in left handed mode
  6070. * @param eye defines the final position of the entity
  6071. * @param target defines where the entity should look at
  6072. * @param up defines the up vector for the entity
  6073. * @returns the new matrix
  6074. */
  6075. Matrix.LookAtLH = function (eye, target, up) {
  6076. var result = Matrix.Zero();
  6077. Matrix.LookAtLHToRef(eye, target, up, result);
  6078. return result;
  6079. };
  6080. /**
  6081. * 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".
  6082. * This function works in left handed mode
  6083. * @param eye defines the final position of the entity
  6084. * @param target defines where the entity should look at
  6085. * @param up defines the up vector for the entity
  6086. * @param result defines the target matrix
  6087. */
  6088. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6089. // Z axis
  6090. target.subtractToRef(eye, this._zAxis);
  6091. this._zAxis.normalize();
  6092. // X axis
  6093. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6094. if (this._xAxis.lengthSquared() === 0) {
  6095. this._xAxis.x = 1.0;
  6096. }
  6097. else {
  6098. this._xAxis.normalize();
  6099. }
  6100. // Y axis
  6101. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6102. this._yAxis.normalize();
  6103. // Eye angles
  6104. var ex = -Vector3.Dot(this._xAxis, eye);
  6105. var ey = -Vector3.Dot(this._yAxis, eye);
  6106. var ez = -Vector3.Dot(this._zAxis, eye);
  6107. 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);
  6108. };
  6109. /**
  6110. * 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"
  6111. * This function works in right handed mode
  6112. * @param eye defines the final position of the entity
  6113. * @param target defines where the entity should look at
  6114. * @param up defines the up vector for the entity
  6115. * @returns the new matrix
  6116. */
  6117. Matrix.LookAtRH = function (eye, target, up) {
  6118. var result = Matrix.Zero();
  6119. Matrix.LookAtRHToRef(eye, target, up, result);
  6120. return result;
  6121. };
  6122. /**
  6123. * 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".
  6124. * This function works in right handed mode
  6125. * @param eye defines the final position of the entity
  6126. * @param target defines where the entity should look at
  6127. * @param up defines the up vector for the entity
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6131. // Z axis
  6132. eye.subtractToRef(target, this._zAxis);
  6133. this._zAxis.normalize();
  6134. // X axis
  6135. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6136. if (this._xAxis.lengthSquared() === 0) {
  6137. this._xAxis.x = 1.0;
  6138. }
  6139. else {
  6140. this._xAxis.normalize();
  6141. }
  6142. // Y axis
  6143. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6144. this._yAxis.normalize();
  6145. // Eye angles
  6146. var ex = -Vector3.Dot(this._xAxis, eye);
  6147. var ey = -Vector3.Dot(this._yAxis, eye);
  6148. var ez = -Vector3.Dot(this._zAxis, eye);
  6149. 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);
  6150. };
  6151. /**
  6152. * Create a left-handed orthographic projection matrix
  6153. * @param width defines the viewport width
  6154. * @param height defines the viewport height
  6155. * @param znear defines the near clip plane
  6156. * @param zfar defines the far clip plane
  6157. * @returns a new matrix as a left-handed orthographic projection matrix
  6158. */
  6159. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6160. var matrix = Matrix.Zero();
  6161. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6162. return matrix;
  6163. };
  6164. /**
  6165. * Store a left-handed orthographic projection to a given matrix
  6166. * @param width defines the viewport width
  6167. * @param height defines the viewport height
  6168. * @param znear defines the near clip plane
  6169. * @param zfar defines the far clip plane
  6170. * @param result defines the target matrix
  6171. */
  6172. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6173. var n = znear;
  6174. var f = zfar;
  6175. var a = 2.0 / width;
  6176. var b = 2.0 / height;
  6177. var c = 2.0 / (f - n);
  6178. var d = -(f + n) / (f - n);
  6179. 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);
  6180. };
  6181. /**
  6182. * Create a left-handed orthographic projection matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @returns a new matrix as a left-handed orthographic projection matrix
  6190. */
  6191. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6192. var matrix = Matrix.Zero();
  6193. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6194. return matrix;
  6195. };
  6196. /**
  6197. * Stores a left-handed orthographic projection into a given matrix
  6198. * @param left defines the viewport left coordinate
  6199. * @param right defines the viewport right coordinate
  6200. * @param bottom defines the viewport bottom coordinate
  6201. * @param top defines the viewport top coordinate
  6202. * @param znear defines the near clip plane
  6203. * @param zfar defines the far clip plane
  6204. * @param result defines the target matrix
  6205. */
  6206. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6207. var n = znear;
  6208. var f = zfar;
  6209. var a = 2.0 / (right - left);
  6210. var b = 2.0 / (top - bottom);
  6211. var c = 2.0 / (f - n);
  6212. var d = -(f + n) / (f - n);
  6213. var i0 = (left + right) / (left - right);
  6214. var i1 = (top + bottom) / (bottom - top);
  6215. 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);
  6216. };
  6217. /**
  6218. * Creates a right-handed orthographic projection matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a right-handed orthographic projection matrix
  6226. */
  6227. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6230. return matrix;
  6231. };
  6232. /**
  6233. * Stores a right-handed orthographic projection into a given matrix
  6234. * @param left defines the viewport left coordinate
  6235. * @param right defines the viewport right coordinate
  6236. * @param bottom defines the viewport bottom coordinate
  6237. * @param top defines the viewport top coordinate
  6238. * @param znear defines the near clip plane
  6239. * @param zfar defines the far clip plane
  6240. * @param result defines the target matrix
  6241. */
  6242. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6243. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6244. result.m[10] *= -1.0;
  6245. };
  6246. /**
  6247. * Creates a left-handed perspective projection matrix
  6248. * @param width defines the viewport width
  6249. * @param height defines the viewport height
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @returns a new matrix as a left-handed perspective projection matrix
  6253. */
  6254. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6255. var matrix = Matrix.Zero();
  6256. var n = znear;
  6257. var f = zfar;
  6258. var a = 2.0 * n / width;
  6259. var b = 2.0 * n / height;
  6260. var c = (f + n) / (f - n);
  6261. var d = -2.0 * f * n / (f - n);
  6262. 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);
  6263. return matrix;
  6264. };
  6265. /**
  6266. * Creates a left-handed perspective projection matrix
  6267. * @param fov defines the horizontal field of view
  6268. * @param aspect defines the aspect ratio
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @returns a new matrix as a left-handed perspective projection matrix
  6272. */
  6273. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6274. var matrix = Matrix.Zero();
  6275. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6276. return matrix;
  6277. };
  6278. /**
  6279. * Stores a left-handed perspective projection into a given matrix
  6280. * @param fov defines the horizontal field of view
  6281. * @param aspect defines the aspect ratio
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6286. */
  6287. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6288. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6289. var n = znear;
  6290. var f = zfar;
  6291. var t = 1.0 / (Math.tan(fov * 0.5));
  6292. var a = isVerticalFovFixed ? (t / aspect) : t;
  6293. var b = isVerticalFovFixed ? t : (t * aspect);
  6294. var c = (f + n) / (f - n);
  6295. var d = -2.0 * f * n / (f - n);
  6296. 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);
  6297. };
  6298. /**
  6299. * Creates a right-handed perspective projection matrix
  6300. * @param fov defines the horizontal field of view
  6301. * @param aspect defines the aspect ratio
  6302. * @param znear defines the near clip plane
  6303. * @param zfar defines the far clip plane
  6304. * @returns a new matrix as a right-handed perspective projection matrix
  6305. */
  6306. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6307. var matrix = Matrix.Zero();
  6308. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6309. return matrix;
  6310. };
  6311. /**
  6312. * Stores a right-handed perspective projection into a given matrix
  6313. * @param fov defines the horizontal field of view
  6314. * @param aspect defines the aspect ratio
  6315. * @param znear defines the near clip plane
  6316. * @param zfar defines the far clip plane
  6317. * @param result defines the target matrix
  6318. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6319. */
  6320. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6321. //alternatively this could be expressed as:
  6322. // m = PerspectiveFovLHToRef
  6323. // m[10] *= -1.0;
  6324. // m[11] *= -1.0;
  6325. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6326. var n = znear;
  6327. var f = zfar;
  6328. var t = 1.0 / (Math.tan(fov * 0.5));
  6329. var a = isVerticalFovFixed ? (t / aspect) : t;
  6330. var b = isVerticalFovFixed ? t : (t * aspect);
  6331. var c = -(f + n) / (f - n);
  6332. var d = -2 * f * n / (f - n);
  6333. 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);
  6334. };
  6335. /**
  6336. * Stores a perspective projection for WebVR info a given matrix
  6337. * @param fov defines the field of view
  6338. * @param znear defines the near clip plane
  6339. * @param zfar defines the far clip plane
  6340. * @param result defines the target matrix
  6341. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6342. */
  6343. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6344. if (rightHanded === void 0) { rightHanded = false; }
  6345. var rightHandedFactor = rightHanded ? -1 : 1;
  6346. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6347. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6348. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6349. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6350. var xScale = 2.0 / (leftTan + rightTan);
  6351. var yScale = 2.0 / (upTan + downTan);
  6352. result.m[0] = xScale;
  6353. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6354. result.m[5] = yScale;
  6355. result.m[6] = result.m[7] = 0.0;
  6356. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6357. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6358. result.m[10] = -zfar / (znear - zfar);
  6359. result.m[11] = 1.0 * rightHandedFactor;
  6360. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6361. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6362. result._markAsUpdated();
  6363. };
  6364. /**
  6365. * Computes a complete transformation matrix
  6366. * @param viewport defines the viewport to use
  6367. * @param world defines the world matrix
  6368. * @param view defines the view matrix
  6369. * @param projection defines the projection matrix
  6370. * @param zmin defines the near clip plane
  6371. * @param zmax defines the far clip plane
  6372. * @returns the transformation matrix
  6373. */
  6374. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6375. var cw = viewport.width;
  6376. var ch = viewport.height;
  6377. var cx = viewport.x;
  6378. var cy = viewport.y;
  6379. 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);
  6380. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6381. };
  6382. /**
  6383. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6384. * @param matrix defines the matrix to use
  6385. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6386. */
  6387. Matrix.GetAsMatrix2x2 = function (matrix) {
  6388. return new Float32Array([
  6389. matrix.m[0], matrix.m[1],
  6390. matrix.m[4], matrix.m[5]
  6391. ]);
  6392. };
  6393. /**
  6394. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6395. * @param matrix defines the matrix to use
  6396. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6397. */
  6398. Matrix.GetAsMatrix3x3 = function (matrix) {
  6399. return new Float32Array([
  6400. matrix.m[0], matrix.m[1], matrix.m[2],
  6401. matrix.m[4], matrix.m[5], matrix.m[6],
  6402. matrix.m[8], matrix.m[9], matrix.m[10]
  6403. ]);
  6404. };
  6405. /**
  6406. * Compute the transpose of a given matrix
  6407. * @param matrix defines the matrix to transpose
  6408. * @returns the new matrix
  6409. */
  6410. Matrix.Transpose = function (matrix) {
  6411. var result = new Matrix();
  6412. Matrix.TransposeToRef(matrix, result);
  6413. return result;
  6414. };
  6415. /**
  6416. * Compute the transpose of a matrix and store it in a target matrix
  6417. * @param matrix defines the matrix to transpose
  6418. * @param result defines the target matrix
  6419. */
  6420. Matrix.TransposeToRef = function (matrix, result) {
  6421. result.m[0] = matrix.m[0];
  6422. result.m[1] = matrix.m[4];
  6423. result.m[2] = matrix.m[8];
  6424. result.m[3] = matrix.m[12];
  6425. result.m[4] = matrix.m[1];
  6426. result.m[5] = matrix.m[5];
  6427. result.m[6] = matrix.m[9];
  6428. result.m[7] = matrix.m[13];
  6429. result.m[8] = matrix.m[2];
  6430. result.m[9] = matrix.m[6];
  6431. result.m[10] = matrix.m[10];
  6432. result.m[11] = matrix.m[14];
  6433. result.m[12] = matrix.m[3];
  6434. result.m[13] = matrix.m[7];
  6435. result.m[14] = matrix.m[11];
  6436. result.m[15] = matrix.m[15];
  6437. };
  6438. /**
  6439. * Computes a reflection matrix from a plane
  6440. * @param plane defines the reflection plane
  6441. * @returns a new matrix
  6442. */
  6443. Matrix.Reflection = function (plane) {
  6444. var matrix = new Matrix();
  6445. Matrix.ReflectionToRef(plane, matrix);
  6446. return matrix;
  6447. };
  6448. /**
  6449. * Computes a reflection matrix from a plane
  6450. * @param plane defines the reflection plane
  6451. * @param result defines the target matrix
  6452. */
  6453. Matrix.ReflectionToRef = function (plane, result) {
  6454. plane.normalize();
  6455. var x = plane.normal.x;
  6456. var y = plane.normal.y;
  6457. var z = plane.normal.z;
  6458. var temp = -2 * x;
  6459. var temp2 = -2 * y;
  6460. var temp3 = -2 * z;
  6461. result.m[0] = (temp * x) + 1;
  6462. result.m[1] = temp2 * x;
  6463. result.m[2] = temp3 * x;
  6464. result.m[3] = 0.0;
  6465. result.m[4] = temp * y;
  6466. result.m[5] = (temp2 * y) + 1;
  6467. result.m[6] = temp3 * y;
  6468. result.m[7] = 0.0;
  6469. result.m[8] = temp * z;
  6470. result.m[9] = temp2 * z;
  6471. result.m[10] = (temp3 * z) + 1;
  6472. result.m[11] = 0.0;
  6473. result.m[12] = temp * plane.d;
  6474. result.m[13] = temp2 * plane.d;
  6475. result.m[14] = temp3 * plane.d;
  6476. result.m[15] = 1.0;
  6477. result._markAsUpdated();
  6478. };
  6479. /**
  6480. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6481. * @param xaxis defines the value of the 1st axis
  6482. * @param yaxis defines the value of the 2nd axis
  6483. * @param zaxis defines the value of the 3rd axis
  6484. * @param result defines the target matrix
  6485. */
  6486. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6487. result.m[0] = xaxis.x;
  6488. result.m[1] = xaxis.y;
  6489. result.m[2] = xaxis.z;
  6490. result.m[3] = 0.0;
  6491. result.m[4] = yaxis.x;
  6492. result.m[5] = yaxis.y;
  6493. result.m[6] = yaxis.z;
  6494. result.m[7] = 0.0;
  6495. result.m[8] = zaxis.x;
  6496. result.m[9] = zaxis.y;
  6497. result.m[10] = zaxis.z;
  6498. result.m[11] = 0.0;
  6499. result.m[12] = 0.0;
  6500. result.m[13] = 0.0;
  6501. result.m[14] = 0.0;
  6502. result.m[15] = 1.0;
  6503. result._markAsUpdated();
  6504. };
  6505. /**
  6506. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6507. * @param quat defines the quaternion to use
  6508. * @param result defines the target matrix
  6509. */
  6510. Matrix.FromQuaternionToRef = function (quat, result) {
  6511. var xx = quat.x * quat.x;
  6512. var yy = quat.y * quat.y;
  6513. var zz = quat.z * quat.z;
  6514. var xy = quat.x * quat.y;
  6515. var zw = quat.z * quat.w;
  6516. var zx = quat.z * quat.x;
  6517. var yw = quat.y * quat.w;
  6518. var yz = quat.y * quat.z;
  6519. var xw = quat.x * quat.w;
  6520. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6521. result.m[1] = 2.0 * (xy + zw);
  6522. result.m[2] = 2.0 * (zx - yw);
  6523. result.m[3] = 0.0;
  6524. result.m[4] = 2.0 * (xy - zw);
  6525. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6526. result.m[6] = 2.0 * (yz + xw);
  6527. result.m[7] = 0.0;
  6528. result.m[8] = 2.0 * (zx + yw);
  6529. result.m[9] = 2.0 * (yz - xw);
  6530. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6531. result.m[11] = 0.0;
  6532. result.m[12] = 0.0;
  6533. result.m[13] = 0.0;
  6534. result.m[14] = 0.0;
  6535. result.m[15] = 1.0;
  6536. result._markAsUpdated();
  6537. };
  6538. Matrix._tempQuaternion = new Quaternion();
  6539. Matrix._xAxis = Vector3.Zero();
  6540. Matrix._yAxis = Vector3.Zero();
  6541. Matrix._zAxis = Vector3.Zero();
  6542. Matrix._updateFlagSeed = 0;
  6543. Matrix._identityReadOnly = Matrix.Identity();
  6544. return Matrix;
  6545. }());
  6546. BABYLON.Matrix = Matrix;
  6547. var Plane = /** @class */ (function () {
  6548. /**
  6549. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6550. */
  6551. function Plane(a, b, c, d) {
  6552. this.normal = new Vector3(a, b, c);
  6553. this.d = d;
  6554. }
  6555. /**
  6556. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6557. */
  6558. Plane.prototype.asArray = function () {
  6559. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6560. };
  6561. // Methods
  6562. /**
  6563. * Returns a new plane copied from the current Plane.
  6564. */
  6565. Plane.prototype.clone = function () {
  6566. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6567. };
  6568. /**
  6569. * Returns the string "Plane".
  6570. */
  6571. Plane.prototype.getClassName = function () {
  6572. return "Plane";
  6573. };
  6574. /**
  6575. * Returns the Plane hash code.
  6576. */
  6577. Plane.prototype.getHashCode = function () {
  6578. var hash = this.normal.getHashCode();
  6579. hash = (hash * 397) ^ (this.d || 0);
  6580. return hash;
  6581. };
  6582. /**
  6583. * Normalize the current Plane in place.
  6584. * Returns the updated Plane.
  6585. */
  6586. Plane.prototype.normalize = function () {
  6587. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6588. var magnitude = 0.0;
  6589. if (norm !== 0) {
  6590. magnitude = 1.0 / norm;
  6591. }
  6592. this.normal.x *= magnitude;
  6593. this.normal.y *= magnitude;
  6594. this.normal.z *= magnitude;
  6595. this.d *= magnitude;
  6596. return this;
  6597. };
  6598. /**
  6599. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6600. */
  6601. Plane.prototype.transform = function (transformation) {
  6602. var transposedMatrix = Matrix.Transpose(transformation);
  6603. var x = this.normal.x;
  6604. var y = this.normal.y;
  6605. var z = this.normal.z;
  6606. var d = this.d;
  6607. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6608. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6609. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6610. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6611. return new Plane(normalX, normalY, normalZ, finalD);
  6612. };
  6613. /**
  6614. * Returns the dot product (float) of the point coordinates and the plane normal.
  6615. */
  6616. Plane.prototype.dotCoordinate = function (point) {
  6617. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6618. };
  6619. /**
  6620. * Updates the current Plane from the plane defined by the three given points.
  6621. * Returns the updated Plane.
  6622. */
  6623. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6624. var x1 = point2.x - point1.x;
  6625. var y1 = point2.y - point1.y;
  6626. var z1 = point2.z - point1.z;
  6627. var x2 = point3.x - point1.x;
  6628. var y2 = point3.y - point1.y;
  6629. var z2 = point3.z - point1.z;
  6630. var yz = (y1 * z2) - (z1 * y2);
  6631. var xz = (z1 * x2) - (x1 * z2);
  6632. var xy = (x1 * y2) - (y1 * x2);
  6633. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6634. var invPyth;
  6635. if (pyth !== 0) {
  6636. invPyth = 1.0 / pyth;
  6637. }
  6638. else {
  6639. invPyth = 0.0;
  6640. }
  6641. this.normal.x = yz * invPyth;
  6642. this.normal.y = xz * invPyth;
  6643. this.normal.z = xy * invPyth;
  6644. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6645. return this;
  6646. };
  6647. /**
  6648. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6649. */
  6650. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6651. var dot = Vector3.Dot(this.normal, direction);
  6652. return (dot <= epsilon);
  6653. };
  6654. /**
  6655. * Returns the signed distance (float) from the given point to the Plane.
  6656. */
  6657. Plane.prototype.signedDistanceTo = function (point) {
  6658. return Vector3.Dot(point, this.normal) + this.d;
  6659. };
  6660. // Statics
  6661. /**
  6662. * Returns a new Plane from the given array.
  6663. */
  6664. Plane.FromArray = function (array) {
  6665. return new Plane(array[0], array[1], array[2], array[3]);
  6666. };
  6667. /**
  6668. * Returns a new Plane defined by the three given points.
  6669. */
  6670. Plane.FromPoints = function (point1, point2, point3) {
  6671. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6672. result.copyFromPoints(point1, point2, point3);
  6673. return result;
  6674. };
  6675. /**
  6676. * Returns a new Plane the normal vector to this plane at the given origin point.
  6677. * Note : the vector "normal" is updated because normalized.
  6678. */
  6679. Plane.FromPositionAndNormal = function (origin, normal) {
  6680. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6681. normal.normalize();
  6682. result.normal = normal;
  6683. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6684. return result;
  6685. };
  6686. /**
  6687. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6688. */
  6689. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6690. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6691. return Vector3.Dot(point, normal) + d;
  6692. };
  6693. return Plane;
  6694. }());
  6695. BABYLON.Plane = Plane;
  6696. var Viewport = /** @class */ (function () {
  6697. /**
  6698. * Creates a Viewport object located at (x, y) and sized (width, height).
  6699. */
  6700. function Viewport(x, y, width, height) {
  6701. this.x = x;
  6702. this.y = y;
  6703. this.width = width;
  6704. this.height = height;
  6705. }
  6706. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6707. if (renderWidthOrEngine.getRenderWidth) {
  6708. var engine = renderWidthOrEngine;
  6709. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6710. }
  6711. var renderWidth = renderWidthOrEngine;
  6712. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6713. };
  6714. /**
  6715. * Returns a new Viewport copied from the current one.
  6716. */
  6717. Viewport.prototype.clone = function () {
  6718. return new Viewport(this.x, this.y, this.width, this.height);
  6719. };
  6720. return Viewport;
  6721. }());
  6722. BABYLON.Viewport = Viewport;
  6723. var Frustum = /** @class */ (function () {
  6724. function Frustum() {
  6725. }
  6726. /**
  6727. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6728. */
  6729. Frustum.GetPlanes = function (transform) {
  6730. var frustumPlanes = [];
  6731. for (var index = 0; index < 6; index++) {
  6732. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6733. }
  6734. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6735. return frustumPlanes;
  6736. };
  6737. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6738. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6739. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6740. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6741. frustumPlane.d = transform.m[15] + transform.m[14];
  6742. frustumPlane.normalize();
  6743. };
  6744. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6745. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6746. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6747. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6748. frustumPlane.d = transform.m[15] - transform.m[14];
  6749. frustumPlane.normalize();
  6750. };
  6751. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6752. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6753. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6754. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6755. frustumPlane.d = transform.m[15] + transform.m[12];
  6756. frustumPlane.normalize();
  6757. };
  6758. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6759. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6760. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6761. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6762. frustumPlane.d = transform.m[15] - transform.m[12];
  6763. frustumPlane.normalize();
  6764. };
  6765. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6766. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6767. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6768. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6769. frustumPlane.d = transform.m[15] - transform.m[13];
  6770. frustumPlane.normalize();
  6771. };
  6772. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6773. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6774. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6775. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6776. frustumPlane.d = transform.m[15] + transform.m[13];
  6777. frustumPlane.normalize();
  6778. };
  6779. /**
  6780. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6781. */
  6782. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6783. // Near
  6784. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6785. // Far
  6786. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6787. // Left
  6788. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6789. // Right
  6790. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6791. // Top
  6792. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6793. // Bottom
  6794. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6795. };
  6796. return Frustum;
  6797. }());
  6798. BABYLON.Frustum = Frustum;
  6799. /** Defines supported spaces */
  6800. var Space;
  6801. (function (Space) {
  6802. /** Local (object) space */
  6803. Space[Space["LOCAL"] = 0] = "LOCAL";
  6804. /** World space */
  6805. Space[Space["WORLD"] = 1] = "WORLD";
  6806. /** Bone space */
  6807. Space[Space["BONE"] = 2] = "BONE";
  6808. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6809. /** Defines the 3 main axes */
  6810. var Axis = /** @class */ (function () {
  6811. function Axis() {
  6812. }
  6813. /** X axis */
  6814. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6815. /** Y axis */
  6816. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6817. /** Z axis */
  6818. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6819. return Axis;
  6820. }());
  6821. BABYLON.Axis = Axis;
  6822. ;
  6823. var BezierCurve = /** @class */ (function () {
  6824. function BezierCurve() {
  6825. }
  6826. /**
  6827. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6828. */
  6829. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6830. // Extract X (which is equal to time here)
  6831. var f0 = 1 - 3 * x2 + 3 * x1;
  6832. var f1 = 3 * x2 - 6 * x1;
  6833. var f2 = 3 * x1;
  6834. var refinedT = t;
  6835. for (var i = 0; i < 5; i++) {
  6836. var refinedT2 = refinedT * refinedT;
  6837. var refinedT3 = refinedT2 * refinedT;
  6838. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6839. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6840. refinedT -= (x - t) * slope;
  6841. refinedT = Math.min(1, Math.max(0, refinedT));
  6842. }
  6843. // Resolve cubic bezier for the given x
  6844. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6845. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6846. Math.pow(refinedT, 3);
  6847. };
  6848. return BezierCurve;
  6849. }());
  6850. BABYLON.BezierCurve = BezierCurve;
  6851. /**
  6852. * Defines potential orientation for back face culling
  6853. */
  6854. var Orientation;
  6855. (function (Orientation) {
  6856. /**
  6857. * Clockwise
  6858. */
  6859. Orientation[Orientation["CW"] = 0] = "CW";
  6860. /** Counter clockwise */
  6861. Orientation[Orientation["CCW"] = 1] = "CCW";
  6862. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6863. /**
  6864. * Defines angle representation
  6865. */
  6866. var Angle = /** @class */ (function () {
  6867. /**
  6868. * Creates an Angle object of "radians" radians (float).
  6869. */
  6870. function Angle(radians) {
  6871. this._radians = radians;
  6872. if (this._radians < 0.0)
  6873. this._radians += (2.0 * Math.PI);
  6874. }
  6875. /**
  6876. * Get value in degrees
  6877. * @returns the Angle value in degrees (float)
  6878. */
  6879. Angle.prototype.degrees = function () {
  6880. return this._radians * 180.0 / Math.PI;
  6881. };
  6882. /**
  6883. * Get value in radians
  6884. * @returns the Angle value in radians (float)
  6885. */
  6886. Angle.prototype.radians = function () {
  6887. return this._radians;
  6888. };
  6889. /**
  6890. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6891. * @param a defines first vector
  6892. * @param b defines second vector
  6893. * @returns a new Angle
  6894. */
  6895. Angle.BetweenTwoPoints = function (a, b) {
  6896. var delta = b.subtract(a);
  6897. var theta = Math.atan2(delta.y, delta.x);
  6898. return new Angle(theta);
  6899. };
  6900. /**
  6901. * Gets a new Angle object from the given float in radians
  6902. * @param radians defines the angle value in radians
  6903. * @returns a new Angle
  6904. */
  6905. Angle.FromRadians = function (radians) {
  6906. return new Angle(radians);
  6907. };
  6908. /**
  6909. * Gets a new Angle object from the given float in degrees
  6910. * @param degrees defines the angle value in degrees
  6911. * @returns a new Angle
  6912. */
  6913. Angle.FromDegrees = function (degrees) {
  6914. return new Angle(degrees * Math.PI / 180.0);
  6915. };
  6916. return Angle;
  6917. }());
  6918. BABYLON.Angle = Angle;
  6919. var Arc2 = /** @class */ (function () {
  6920. /**
  6921. * Creates an Arc object from the three given points : start, middle and end.
  6922. */
  6923. function Arc2(startPoint, midPoint, endPoint) {
  6924. this.startPoint = startPoint;
  6925. this.midPoint = midPoint;
  6926. this.endPoint = endPoint;
  6927. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6928. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6929. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6930. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6931. 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);
  6932. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6933. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6934. var a1 = this.startAngle.degrees();
  6935. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6936. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6937. // angles correction
  6938. if (a2 - a1 > +180.0)
  6939. a2 -= 360.0;
  6940. if (a2 - a1 < -180.0)
  6941. a2 += 360.0;
  6942. if (a3 - a2 > +180.0)
  6943. a3 -= 360.0;
  6944. if (a3 - a2 < -180.0)
  6945. a3 += 360.0;
  6946. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6947. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6948. }
  6949. return Arc2;
  6950. }());
  6951. BABYLON.Arc2 = Arc2;
  6952. var Path2 = /** @class */ (function () {
  6953. /**
  6954. * Creates a Path2 object from the starting 2D coordinates x and y.
  6955. */
  6956. function Path2(x, y) {
  6957. this._points = new Array();
  6958. this._length = 0.0;
  6959. this.closed = false;
  6960. this._points.push(new Vector2(x, y));
  6961. }
  6962. /**
  6963. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6964. * Returns the updated Path2.
  6965. */
  6966. Path2.prototype.addLineTo = function (x, y) {
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var newPoint = new Vector2(x, y);
  6971. var previousPoint = this._points[this._points.length - 1];
  6972. this._points.push(newPoint);
  6973. this._length += newPoint.subtract(previousPoint).length();
  6974. return this;
  6975. };
  6976. /**
  6977. * 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.
  6978. * Returns the updated Path2.
  6979. */
  6980. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6981. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6982. if (this.closed) {
  6983. return this;
  6984. }
  6985. var startPoint = this._points[this._points.length - 1];
  6986. var midPoint = new Vector2(midX, midY);
  6987. var endPoint = new Vector2(endX, endY);
  6988. var arc = new Arc2(startPoint, midPoint, endPoint);
  6989. var increment = arc.angle.radians() / numberOfSegments;
  6990. if (arc.orientation === Orientation.CW)
  6991. increment *= -1;
  6992. var currentAngle = arc.startAngle.radians() + increment;
  6993. for (var i = 0; i < numberOfSegments; i++) {
  6994. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6995. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6996. this.addLineTo(x, y);
  6997. currentAngle += increment;
  6998. }
  6999. return this;
  7000. };
  7001. /**
  7002. * Closes the Path2.
  7003. * Returns the Path2.
  7004. */
  7005. Path2.prototype.close = function () {
  7006. this.closed = true;
  7007. return this;
  7008. };
  7009. /**
  7010. * Returns the Path2 total length (float).
  7011. */
  7012. Path2.prototype.length = function () {
  7013. var result = this._length;
  7014. if (!this.closed) {
  7015. var lastPoint = this._points[this._points.length - 1];
  7016. var firstPoint = this._points[0];
  7017. result += (firstPoint.subtract(lastPoint).length());
  7018. }
  7019. return result;
  7020. };
  7021. /**
  7022. * Returns the Path2 internal array of points.
  7023. */
  7024. Path2.prototype.getPoints = function () {
  7025. return this._points;
  7026. };
  7027. /**
  7028. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7029. */
  7030. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7031. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7032. return Vector2.Zero();
  7033. }
  7034. var lengthPosition = normalizedLengthPosition * this.length();
  7035. var previousOffset = 0;
  7036. for (var i = 0; i < this._points.length; i++) {
  7037. var j = (i + 1) % this._points.length;
  7038. var a = this._points[i];
  7039. var b = this._points[j];
  7040. var bToA = b.subtract(a);
  7041. var nextOffset = (bToA.length() + previousOffset);
  7042. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7043. var dir = bToA.normalize();
  7044. var localOffset = lengthPosition - previousOffset;
  7045. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7046. }
  7047. previousOffset = nextOffset;
  7048. }
  7049. return Vector2.Zero();
  7050. };
  7051. /**
  7052. * Returns a new Path2 starting at the coordinates (x, y).
  7053. */
  7054. Path2.StartingAt = function (x, y) {
  7055. return new Path2(x, y);
  7056. };
  7057. return Path2;
  7058. }());
  7059. BABYLON.Path2 = Path2;
  7060. var Path3D = /** @class */ (function () {
  7061. /**
  7062. * new Path3D(path, normal, raw)
  7063. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7064. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7065. * path : an array of Vector3, the curve axis of the Path3D
  7066. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7067. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7068. */
  7069. function Path3D(path, firstNormal, raw) {
  7070. if (firstNormal === void 0) { firstNormal = null; }
  7071. this.path = path;
  7072. this._curve = new Array();
  7073. this._distances = new Array();
  7074. this._tangents = new Array();
  7075. this._normals = new Array();
  7076. this._binormals = new Array();
  7077. for (var p = 0; p < path.length; p++) {
  7078. this._curve[p] = path[p].clone(); // hard copy
  7079. }
  7080. this._raw = raw || false;
  7081. this._compute(firstNormal);
  7082. }
  7083. /**
  7084. * Returns the Path3D array of successive Vector3 designing its curve.
  7085. */
  7086. Path3D.prototype.getCurve = function () {
  7087. return this._curve;
  7088. };
  7089. /**
  7090. * Returns an array populated with tangent vectors on each Path3D curve point.
  7091. */
  7092. Path3D.prototype.getTangents = function () {
  7093. return this._tangents;
  7094. };
  7095. /**
  7096. * Returns an array populated with normal vectors on each Path3D curve point.
  7097. */
  7098. Path3D.prototype.getNormals = function () {
  7099. return this._normals;
  7100. };
  7101. /**
  7102. * Returns an array populated with binormal vectors on each Path3D curve point.
  7103. */
  7104. Path3D.prototype.getBinormals = function () {
  7105. return this._binormals;
  7106. };
  7107. /**
  7108. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7109. */
  7110. Path3D.prototype.getDistances = function () {
  7111. return this._distances;
  7112. };
  7113. /**
  7114. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7115. * Returns the same object updated.
  7116. */
  7117. Path3D.prototype.update = function (path, firstNormal) {
  7118. if (firstNormal === void 0) { firstNormal = null; }
  7119. for (var p = 0; p < path.length; p++) {
  7120. this._curve[p].x = path[p].x;
  7121. this._curve[p].y = path[p].y;
  7122. this._curve[p].z = path[p].z;
  7123. }
  7124. this._compute(firstNormal);
  7125. return this;
  7126. };
  7127. // private function compute() : computes tangents, normals and binormals
  7128. Path3D.prototype._compute = function (firstNormal) {
  7129. var l = this._curve.length;
  7130. // first and last tangents
  7131. this._tangents[0] = this._getFirstNonNullVector(0);
  7132. if (!this._raw) {
  7133. this._tangents[0].normalize();
  7134. }
  7135. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7136. if (!this._raw) {
  7137. this._tangents[l - 1].normalize();
  7138. }
  7139. // normals and binormals at first point : arbitrary vector with _normalVector()
  7140. var tg0 = this._tangents[0];
  7141. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7142. this._normals[0] = pp0;
  7143. if (!this._raw) {
  7144. this._normals[0].normalize();
  7145. }
  7146. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7147. if (!this._raw) {
  7148. this._binormals[0].normalize();
  7149. }
  7150. this._distances[0] = 0.0;
  7151. // normals and binormals : next points
  7152. var prev; // previous vector (segment)
  7153. var cur; // current vector (segment)
  7154. var curTang; // current tangent
  7155. // previous normal
  7156. var prevBinor; // previous binormal
  7157. for (var i = 1; i < l; i++) {
  7158. // tangents
  7159. prev = this._getLastNonNullVector(i);
  7160. if (i < l - 1) {
  7161. cur = this._getFirstNonNullVector(i);
  7162. this._tangents[i] = prev.add(cur);
  7163. this._tangents[i].normalize();
  7164. }
  7165. this._distances[i] = this._distances[i - 1] + prev.length();
  7166. // normals and binormals
  7167. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7168. curTang = this._tangents[i];
  7169. prevBinor = this._binormals[i - 1];
  7170. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7171. if (!this._raw) {
  7172. this._normals[i].normalize();
  7173. }
  7174. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7175. if (!this._raw) {
  7176. this._binormals[i].normalize();
  7177. }
  7178. }
  7179. };
  7180. // private function getFirstNonNullVector(index)
  7181. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7182. Path3D.prototype._getFirstNonNullVector = function (index) {
  7183. var i = 1;
  7184. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7185. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7186. i++;
  7187. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7188. }
  7189. return nNVector;
  7190. };
  7191. // private function getLastNonNullVector(index)
  7192. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7193. Path3D.prototype._getLastNonNullVector = function (index) {
  7194. var i = 1;
  7195. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7196. while (nLVector.length() === 0 && index > i + 1) {
  7197. i++;
  7198. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7199. }
  7200. return nLVector;
  7201. };
  7202. // private function normalVector(v0, vt, va) :
  7203. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7204. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7205. Path3D.prototype._normalVector = function (v0, vt, va) {
  7206. var normal0;
  7207. var tgl = vt.length();
  7208. if (tgl === 0.0) {
  7209. tgl = 1.0;
  7210. }
  7211. if (va === undefined || va === null) {
  7212. var point;
  7213. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7214. point = new Vector3(0.0, -1.0, 0.0);
  7215. }
  7216. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7217. point = new Vector3(1.0, 0.0, 0.0);
  7218. }
  7219. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7220. point = new Vector3(0.0, 0.0, 1.0);
  7221. }
  7222. else {
  7223. point = Vector3.Zero();
  7224. }
  7225. normal0 = Vector3.Cross(vt, point);
  7226. }
  7227. else {
  7228. normal0 = Vector3.Cross(vt, va);
  7229. Vector3.CrossToRef(normal0, vt, normal0);
  7230. }
  7231. normal0.normalize();
  7232. return normal0;
  7233. };
  7234. return Path3D;
  7235. }());
  7236. BABYLON.Path3D = Path3D;
  7237. var Curve3 = /** @class */ (function () {
  7238. /**
  7239. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7240. * A Curve3 is designed from a series of successive Vector3.
  7241. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7242. */
  7243. function Curve3(points) {
  7244. this._length = 0.0;
  7245. this._points = points;
  7246. this._length = this._computeLength(points);
  7247. }
  7248. /**
  7249. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7250. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7251. * @param v1 (Vector3) the control point
  7252. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7253. * @param nbPoints (integer) the wanted number of points in the curve
  7254. */
  7255. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7256. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7257. var bez = new Array();
  7258. var equation = function (t, val0, val1, val2) {
  7259. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7260. return res;
  7261. };
  7262. for (var i = 0; i <= nbPoints; i++) {
  7263. 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)));
  7264. }
  7265. return new Curve3(bez);
  7266. };
  7267. /**
  7268. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7269. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7270. * @param v1 (Vector3) the first control point
  7271. * @param v2 (Vector3) the second control point
  7272. * @param v3 (Vector3) the end point of the Cubic Bezier
  7273. * @param nbPoints (integer) the wanted number of points in the curve
  7274. */
  7275. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7276. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7277. var bez = new Array();
  7278. var equation = function (t, val0, val1, val2, val3) {
  7279. 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;
  7280. return res;
  7281. };
  7282. for (var i = 0; i <= nbPoints; i++) {
  7283. 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)));
  7284. }
  7285. return new Curve3(bez);
  7286. };
  7287. /**
  7288. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7289. * @param p1 (Vector3) the origin point of the Hermite Spline
  7290. * @param t1 (Vector3) the tangent vector at the origin point
  7291. * @param p2 (Vector3) the end point of the Hermite Spline
  7292. * @param t2 (Vector3) the tangent vector at the end point
  7293. * @param nbPoints (integer) the wanted number of points in the curve
  7294. */
  7295. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7296. var hermite = new Array();
  7297. var step = 1.0 / nbPoints;
  7298. for (var i = 0; i <= nbPoints; i++) {
  7299. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7300. }
  7301. return new Curve3(hermite);
  7302. };
  7303. /**
  7304. * Returns a Curve3 object along a CatmullRom Spline curve :
  7305. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7306. * @param nbPoints (integer) the wanted number of points between each curve control points
  7307. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7308. */
  7309. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7310. var catmullRom = new Array();
  7311. var step = 1.0 / nbPoints;
  7312. var amount = 0.0;
  7313. if (closed) {
  7314. var pointsCount = points.length;
  7315. for (var i = 0; i < pointsCount; i++) {
  7316. amount = 0;
  7317. for (var c = 0; c < nbPoints; c++) {
  7318. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7319. amount += step;
  7320. }
  7321. }
  7322. catmullRom.push(catmullRom[0]);
  7323. }
  7324. else {
  7325. var totalPoints = new Array();
  7326. totalPoints.push(points[0].clone());
  7327. Array.prototype.push.apply(totalPoints, points);
  7328. totalPoints.push(points[points.length - 1].clone());
  7329. for (var i = 0; i < totalPoints.length - 3; i++) {
  7330. amount = 0;
  7331. for (var c = 0; c < nbPoints; c++) {
  7332. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7333. amount += step;
  7334. }
  7335. }
  7336. i--;
  7337. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7338. }
  7339. return new Curve3(catmullRom);
  7340. };
  7341. /**
  7342. * Returns the Curve3 stored array of successive Vector3
  7343. */
  7344. Curve3.prototype.getPoints = function () {
  7345. return this._points;
  7346. };
  7347. /**
  7348. * Returns the computed length (float) of the curve.
  7349. */
  7350. Curve3.prototype.length = function () {
  7351. return this._length;
  7352. };
  7353. /**
  7354. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7355. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7356. * curveA and curveB keep unchanged.
  7357. */
  7358. Curve3.prototype.continue = function (curve) {
  7359. var lastPoint = this._points[this._points.length - 1];
  7360. var continuedPoints = this._points.slice();
  7361. var curvePoints = curve.getPoints();
  7362. for (var i = 1; i < curvePoints.length; i++) {
  7363. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7364. }
  7365. var continuedCurve = new Curve3(continuedPoints);
  7366. return continuedCurve;
  7367. };
  7368. Curve3.prototype._computeLength = function (path) {
  7369. var l = 0;
  7370. for (var i = 1; i < path.length; i++) {
  7371. l += (path[i].subtract(path[i - 1])).length();
  7372. }
  7373. return l;
  7374. };
  7375. return Curve3;
  7376. }());
  7377. BABYLON.Curve3 = Curve3;
  7378. // Vertex formats
  7379. var PositionNormalVertex = /** @class */ (function () {
  7380. function PositionNormalVertex(position, normal) {
  7381. if (position === void 0) { position = Vector3.Zero(); }
  7382. if (normal === void 0) { normal = Vector3.Up(); }
  7383. this.position = position;
  7384. this.normal = normal;
  7385. }
  7386. PositionNormalVertex.prototype.clone = function () {
  7387. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7388. };
  7389. return PositionNormalVertex;
  7390. }());
  7391. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7392. var PositionNormalTextureVertex = /** @class */ (function () {
  7393. function PositionNormalTextureVertex(position, normal, uv) {
  7394. if (position === void 0) { position = Vector3.Zero(); }
  7395. if (normal === void 0) { normal = Vector3.Up(); }
  7396. if (uv === void 0) { uv = Vector2.Zero(); }
  7397. this.position = position;
  7398. this.normal = normal;
  7399. this.uv = uv;
  7400. }
  7401. PositionNormalTextureVertex.prototype.clone = function () {
  7402. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7403. };
  7404. return PositionNormalTextureVertex;
  7405. }());
  7406. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7407. // Temporary pre-allocated objects for engine internal use
  7408. // usage in any internal function :
  7409. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7410. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7411. var Tmp = /** @class */ (function () {
  7412. function Tmp() {
  7413. }
  7414. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7415. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7416. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7417. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7418. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7419. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7420. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7421. Matrix.Zero(), Matrix.Zero(),
  7422. Matrix.Zero(), Matrix.Zero(),
  7423. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7424. return Tmp;
  7425. }());
  7426. BABYLON.Tmp = Tmp;
  7427. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7428. var MathTmp = /** @class */ (function () {
  7429. function MathTmp() {
  7430. }
  7431. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7432. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7433. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7434. return MathTmp;
  7435. }());
  7436. })(BABYLON || (BABYLON = {}));
  7437. //# sourceMappingURL=babylon.math.js.map
  7438. var BABYLON;
  7439. (function (BABYLON) {
  7440. var Scalar = /** @class */ (function () {
  7441. function Scalar() {
  7442. }
  7443. /**
  7444. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7445. */
  7446. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7447. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7448. var num = a - b;
  7449. return -epsilon <= num && num <= epsilon;
  7450. };
  7451. /**
  7452. * Returns a string : the upper case translation of the number i to hexadecimal.
  7453. */
  7454. Scalar.ToHex = function (i) {
  7455. var str = i.toString(16);
  7456. if (i <= 15) {
  7457. return ("0" + str).toUpperCase();
  7458. }
  7459. return str.toUpperCase();
  7460. };
  7461. /**
  7462. * Returns -1 if value is negative and +1 is value is positive.
  7463. * Returns the value itself if it's equal to zero.
  7464. */
  7465. Scalar.Sign = function (value) {
  7466. value = +value; // convert to a number
  7467. if (value === 0 || isNaN(value))
  7468. return value;
  7469. return value > 0 ? 1 : -1;
  7470. };
  7471. /**
  7472. * Returns the value itself if it's between min and max.
  7473. * Returns min if the value is lower than min.
  7474. * Returns max if the value is greater than max.
  7475. */
  7476. Scalar.Clamp = function (value, min, max) {
  7477. if (min === void 0) { min = 0; }
  7478. if (max === void 0) { max = 1; }
  7479. return Math.min(max, Math.max(min, value));
  7480. };
  7481. /**
  7482. * Returns the log2 of value.
  7483. */
  7484. Scalar.Log2 = function (value) {
  7485. return Math.log(value) * Math.LOG2E;
  7486. };
  7487. /**
  7488. * Loops the value, so that it is never larger than length and never smaller than 0.
  7489. *
  7490. * This is similar to the modulo operator but it works with floating point numbers.
  7491. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7492. * With t = 5 and length = 2.5, the result would be 0.0.
  7493. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7494. */
  7495. Scalar.Repeat = function (value, length) {
  7496. return value - Math.floor(value / length) * length;
  7497. };
  7498. /**
  7499. * Normalize the value between 0.0 and 1.0 using min and max values
  7500. */
  7501. Scalar.Normalize = function (value, min, max) {
  7502. return (value - min) / (max - min);
  7503. };
  7504. /**
  7505. * Denormalize the value from 0.0 and 1.0 using min and max values
  7506. */
  7507. Scalar.Denormalize = function (normalized, min, max) {
  7508. return (normalized * (max - min) + min);
  7509. };
  7510. /**
  7511. * Calculates the shortest difference between two given angles given in degrees.
  7512. */
  7513. Scalar.DeltaAngle = function (current, target) {
  7514. var num = Scalar.Repeat(target - current, 360.0);
  7515. if (num > 180.0) {
  7516. num -= 360.0;
  7517. }
  7518. return num;
  7519. };
  7520. /**
  7521. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7522. *
  7523. * The returned value will move back and forth between 0 and length
  7524. */
  7525. Scalar.PingPong = function (tx, length) {
  7526. var t = Scalar.Repeat(tx, length * 2.0);
  7527. return length - Math.abs(t - length);
  7528. };
  7529. /**
  7530. * Interpolates between min and max with smoothing at the limits.
  7531. *
  7532. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7533. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7534. */
  7535. Scalar.SmoothStep = function (from, to, tx) {
  7536. var t = Scalar.Clamp(tx);
  7537. t = -2.0 * t * t * t + 3.0 * t * t;
  7538. return to * t + from * (1.0 - t);
  7539. };
  7540. /**
  7541. * Moves a value current towards target.
  7542. *
  7543. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7544. * Negative values of maxDelta pushes the value away from target.
  7545. */
  7546. Scalar.MoveTowards = function (current, target, maxDelta) {
  7547. var result = 0;
  7548. if (Math.abs(target - current) <= maxDelta) {
  7549. result = target;
  7550. }
  7551. else {
  7552. result = current + Scalar.Sign(target - current) * maxDelta;
  7553. }
  7554. return result;
  7555. };
  7556. /**
  7557. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7558. *
  7559. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7560. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7561. */
  7562. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7563. var num = Scalar.DeltaAngle(current, target);
  7564. var result = 0;
  7565. if (-maxDelta < num && num < maxDelta) {
  7566. result = target;
  7567. }
  7568. else {
  7569. target = current + num;
  7570. result = Scalar.MoveTowards(current, target, maxDelta);
  7571. }
  7572. return result;
  7573. };
  7574. /**
  7575. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7576. */
  7577. Scalar.Lerp = function (start, end, amount) {
  7578. return start + ((end - start) * amount);
  7579. };
  7580. /**
  7581. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7582. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7583. */
  7584. Scalar.LerpAngle = function (start, end, amount) {
  7585. var num = Scalar.Repeat(end - start, 360.0);
  7586. if (num > 180.0) {
  7587. num -= 360.0;
  7588. }
  7589. return start + num * Scalar.Clamp(amount);
  7590. };
  7591. /**
  7592. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7593. */
  7594. Scalar.InverseLerp = function (a, b, value) {
  7595. var result = 0;
  7596. if (a != b) {
  7597. result = Scalar.Clamp((value - a) / (b - a));
  7598. }
  7599. else {
  7600. result = 0.0;
  7601. }
  7602. return result;
  7603. };
  7604. /**
  7605. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7606. */
  7607. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7608. var squared = amount * amount;
  7609. var cubed = amount * squared;
  7610. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7611. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7612. var part3 = (cubed - (2.0 * squared)) + amount;
  7613. var part4 = cubed - squared;
  7614. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7615. };
  7616. /**
  7617. * Returns a random float number between and min and max values
  7618. */
  7619. Scalar.RandomRange = function (min, max) {
  7620. if (min === max)
  7621. return min;
  7622. return ((Math.random() * (max - min)) + min);
  7623. };
  7624. /**
  7625. * This function returns percentage of a number in a given range.
  7626. *
  7627. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7628. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7629. */
  7630. Scalar.RangeToPercent = function (number, min, max) {
  7631. return ((number - min) / (max - min));
  7632. };
  7633. /**
  7634. * This function returns number that corresponds to the percentage in a given range.
  7635. *
  7636. * PercentToRange(0.34,0,100) will return 34.
  7637. */
  7638. Scalar.PercentToRange = function (percent, min, max) {
  7639. return ((max - min) * percent + min);
  7640. };
  7641. /**
  7642. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7643. * @param angle The angle to normalize in radian.
  7644. * @return The converted angle.
  7645. */
  7646. Scalar.NormalizeRadians = function (angle) {
  7647. // More precise but slower version kept for reference.
  7648. // angle = angle % Tools.TwoPi;
  7649. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7650. //if (angle > Math.PI) {
  7651. // angle -= Tools.TwoPi;
  7652. //}
  7653. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7654. return angle;
  7655. };
  7656. /**
  7657. * Two pi constants convenient for computation.
  7658. */
  7659. Scalar.TwoPi = Math.PI * 2;
  7660. return Scalar;
  7661. }());
  7662. BABYLON.Scalar = Scalar;
  7663. })(BABYLON || (BABYLON = {}));
  7664. //# sourceMappingURL=babylon.math.scalar.js.map
  7665. //# sourceMappingURL=babylon.mixins.js.map
  7666. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7667. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7668. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7669. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7670. //# sourceMappingURL=babylon.webgl2.js.map
  7671. var BABYLON;
  7672. (function (BABYLON) {
  7673. var __decoratorInitialStore = {};
  7674. var __mergedStore = {};
  7675. var _copySource = function (creationFunction, source, instanciate) {
  7676. var destination = creationFunction();
  7677. // Tags
  7678. if (BABYLON.Tags) {
  7679. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7680. }
  7681. var classStore = getMergedStore(destination);
  7682. // Properties
  7683. for (var property in classStore) {
  7684. var propertyDescriptor = classStore[property];
  7685. var sourceProperty = source[property];
  7686. var propertyType = propertyDescriptor.type;
  7687. if (sourceProperty !== undefined && sourceProperty !== null) {
  7688. switch (propertyType) {
  7689. case 0: // Value
  7690. case 6: // Mesh reference
  7691. case 11: // Camera reference
  7692. destination[property] = sourceProperty;
  7693. break;
  7694. case 1: // Texture
  7695. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7696. break;
  7697. case 2: // Color3
  7698. case 3: // FresnelParameters
  7699. case 4: // Vector2
  7700. case 5: // Vector3
  7701. case 7: // Color Curves
  7702. case 10: // Quaternion
  7703. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7704. break;
  7705. }
  7706. }
  7707. }
  7708. return destination;
  7709. };
  7710. function getDirectStore(target) {
  7711. var classKey = target.getClassName();
  7712. if (!__decoratorInitialStore[classKey]) {
  7713. __decoratorInitialStore[classKey] = {};
  7714. }
  7715. return __decoratorInitialStore[classKey];
  7716. }
  7717. /**
  7718. * Return the list of properties flagged as serializable
  7719. * @param target: host object
  7720. */
  7721. function getMergedStore(target) {
  7722. var classKey = target.getClassName();
  7723. if (__mergedStore[classKey]) {
  7724. return __mergedStore[classKey];
  7725. }
  7726. __mergedStore[classKey] = {};
  7727. var store = __mergedStore[classKey];
  7728. var currentTarget = target;
  7729. var currentKey = classKey;
  7730. while (currentKey) {
  7731. var initialStore = __decoratorInitialStore[currentKey];
  7732. for (var property in initialStore) {
  7733. store[property] = initialStore[property];
  7734. }
  7735. var parent_1 = void 0;
  7736. var done = false;
  7737. do {
  7738. parent_1 = Object.getPrototypeOf(currentTarget);
  7739. if (!parent_1.getClassName) {
  7740. done = true;
  7741. break;
  7742. }
  7743. if (parent_1.getClassName() !== currentKey) {
  7744. break;
  7745. }
  7746. currentTarget = parent_1;
  7747. } while (parent_1);
  7748. if (done) {
  7749. break;
  7750. }
  7751. currentKey = parent_1.getClassName();
  7752. currentTarget = parent_1;
  7753. }
  7754. return store;
  7755. }
  7756. function generateSerializableMember(type, sourceName) {
  7757. return function (target, propertyKey) {
  7758. var classStore = getDirectStore(target);
  7759. if (!classStore[propertyKey]) {
  7760. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7761. }
  7762. };
  7763. }
  7764. function generateExpandMember(setCallback, targetKey) {
  7765. if (targetKey === void 0) { targetKey = null; }
  7766. return function (target, propertyKey) {
  7767. var key = targetKey || ("_" + propertyKey);
  7768. Object.defineProperty(target, propertyKey, {
  7769. get: function () {
  7770. return this[key];
  7771. },
  7772. set: function (value) {
  7773. if (this[key] === value) {
  7774. return;
  7775. }
  7776. this[key] = value;
  7777. target[setCallback].apply(this);
  7778. },
  7779. enumerable: true,
  7780. configurable: true
  7781. });
  7782. };
  7783. }
  7784. function expandToProperty(callback, targetKey) {
  7785. if (targetKey === void 0) { targetKey = null; }
  7786. return generateExpandMember(callback, targetKey);
  7787. }
  7788. BABYLON.expandToProperty = expandToProperty;
  7789. function serialize(sourceName) {
  7790. return generateSerializableMember(0, sourceName); // value member
  7791. }
  7792. BABYLON.serialize = serialize;
  7793. function serializeAsTexture(sourceName) {
  7794. return generateSerializableMember(1, sourceName); // texture member
  7795. }
  7796. BABYLON.serializeAsTexture = serializeAsTexture;
  7797. function serializeAsColor3(sourceName) {
  7798. return generateSerializableMember(2, sourceName); // color3 member
  7799. }
  7800. BABYLON.serializeAsColor3 = serializeAsColor3;
  7801. function serializeAsFresnelParameters(sourceName) {
  7802. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7803. }
  7804. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7805. function serializeAsVector2(sourceName) {
  7806. return generateSerializableMember(4, sourceName); // vector2 member
  7807. }
  7808. BABYLON.serializeAsVector2 = serializeAsVector2;
  7809. function serializeAsVector3(sourceName) {
  7810. return generateSerializableMember(5, sourceName); // vector3 member
  7811. }
  7812. BABYLON.serializeAsVector3 = serializeAsVector3;
  7813. function serializeAsMeshReference(sourceName) {
  7814. return generateSerializableMember(6, sourceName); // mesh reference member
  7815. }
  7816. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7817. function serializeAsColorCurves(sourceName) {
  7818. return generateSerializableMember(7, sourceName); // color curves
  7819. }
  7820. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7821. function serializeAsColor4(sourceName) {
  7822. return generateSerializableMember(8, sourceName); // color 4
  7823. }
  7824. BABYLON.serializeAsColor4 = serializeAsColor4;
  7825. function serializeAsImageProcessingConfiguration(sourceName) {
  7826. return generateSerializableMember(9, sourceName); // image processing
  7827. }
  7828. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7829. function serializeAsQuaternion(sourceName) {
  7830. return generateSerializableMember(10, sourceName); // quaternion member
  7831. }
  7832. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7833. /**
  7834. * Decorator used to define property that can be serialized as reference to a camera
  7835. * @param sourceName defines the name of the property to decorate
  7836. */
  7837. function serializeAsCameraReference(sourceName) {
  7838. return generateSerializableMember(11, sourceName); // camera reference member
  7839. }
  7840. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7841. var SerializationHelper = /** @class */ (function () {
  7842. function SerializationHelper() {
  7843. }
  7844. SerializationHelper.Serialize = function (entity, serializationObject) {
  7845. if (!serializationObject) {
  7846. serializationObject = {};
  7847. }
  7848. // Tags
  7849. if (BABYLON.Tags) {
  7850. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7851. }
  7852. var serializedProperties = getMergedStore(entity);
  7853. // Properties
  7854. for (var property in serializedProperties) {
  7855. var propertyDescriptor = serializedProperties[property];
  7856. var targetPropertyName = propertyDescriptor.sourceName || property;
  7857. var propertyType = propertyDescriptor.type;
  7858. var sourceProperty = entity[property];
  7859. if (sourceProperty !== undefined && sourceProperty !== null) {
  7860. switch (propertyType) {
  7861. case 0: // Value
  7862. serializationObject[targetPropertyName] = sourceProperty;
  7863. break;
  7864. case 1: // Texture
  7865. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7866. break;
  7867. case 2: // Color3
  7868. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7869. break;
  7870. case 3: // FresnelParameters
  7871. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7872. break;
  7873. case 4: // Vector2
  7874. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7875. break;
  7876. case 5: // Vector3
  7877. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7878. break;
  7879. case 6: // Mesh reference
  7880. serializationObject[targetPropertyName] = sourceProperty.id;
  7881. break;
  7882. case 7: // Color Curves
  7883. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7884. break;
  7885. case 8: // Color 4
  7886. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7887. break;
  7888. case 9: // Image Processing
  7889. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7890. break;
  7891. case 10: // Quaternion
  7892. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7893. break;
  7894. case 11: // Camera reference
  7895. serializationObject[targetPropertyName] = sourceProperty.id;
  7896. break;
  7897. }
  7898. }
  7899. }
  7900. return serializationObject;
  7901. };
  7902. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7903. if (rootUrl === void 0) { rootUrl = null; }
  7904. var destination = creationFunction();
  7905. if (!rootUrl) {
  7906. rootUrl = "";
  7907. }
  7908. // Tags
  7909. if (BABYLON.Tags) {
  7910. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7911. }
  7912. var classStore = getMergedStore(destination);
  7913. // Properties
  7914. for (var property in classStore) {
  7915. var propertyDescriptor = classStore[property];
  7916. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7917. var propertyType = propertyDescriptor.type;
  7918. if (sourceProperty !== undefined && sourceProperty !== null) {
  7919. var dest = destination;
  7920. switch (propertyType) {
  7921. case 0: // Value
  7922. dest[property] = sourceProperty;
  7923. break;
  7924. case 1: // Texture
  7925. if (scene) {
  7926. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7927. }
  7928. break;
  7929. case 2: // Color3
  7930. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7931. break;
  7932. case 3: // FresnelParameters
  7933. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7934. break;
  7935. case 4: // Vector2
  7936. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7937. break;
  7938. case 5: // Vector3
  7939. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7940. break;
  7941. case 6: // Mesh reference
  7942. if (scene) {
  7943. dest[property] = scene.getLastMeshByID(sourceProperty);
  7944. }
  7945. break;
  7946. case 7: // Color Curves
  7947. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7948. break;
  7949. case 8: // Color 4
  7950. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7951. break;
  7952. case 9: // Image Processing
  7953. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7954. break;
  7955. case 10: // Quaternion
  7956. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7957. break;
  7958. case 11: // Camera reference
  7959. if (scene) {
  7960. dest[property] = scene.getCameraByID(sourceProperty);
  7961. }
  7962. break;
  7963. }
  7964. }
  7965. }
  7966. return destination;
  7967. };
  7968. SerializationHelper.Clone = function (creationFunction, source) {
  7969. return _copySource(creationFunction, source, false);
  7970. };
  7971. SerializationHelper.Instanciate = function (creationFunction, source) {
  7972. return _copySource(creationFunction, source, true);
  7973. };
  7974. return SerializationHelper;
  7975. }());
  7976. BABYLON.SerializationHelper = SerializationHelper;
  7977. })(BABYLON || (BABYLON = {}));
  7978. //# sourceMappingURL=babylon.decorators.js.map
  7979. var BABYLON;
  7980. (function (BABYLON) {
  7981. /**
  7982. * Wrapper class for promise with external resolve and reject.
  7983. */
  7984. var Deferred = /** @class */ (function () {
  7985. /**
  7986. * Constructor for this deferred object.
  7987. */
  7988. function Deferred() {
  7989. var _this = this;
  7990. this.promise = new Promise(function (resolve, reject) {
  7991. _this._resolve = resolve;
  7992. _this._reject = reject;
  7993. });
  7994. }
  7995. Object.defineProperty(Deferred.prototype, "resolve", {
  7996. /**
  7997. * The resolve method of the promise associated with this deferred object.
  7998. */
  7999. get: function () {
  8000. return this._resolve;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Deferred.prototype, "reject", {
  8006. /**
  8007. * The reject method of the promise associated with this deferred object.
  8008. */
  8009. get: function () {
  8010. return this._reject;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. return Deferred;
  8016. }());
  8017. BABYLON.Deferred = Deferred;
  8018. })(BABYLON || (BABYLON = {}));
  8019. //# sourceMappingURL=babylon.deferred.js.map
  8020. var BABYLON;
  8021. (function (BABYLON) {
  8022. /**
  8023. * A class serves as a medium between the observable and its observers
  8024. */
  8025. var EventState = /** @class */ (function () {
  8026. /**
  8027. * Create a new EventState
  8028. * @param mask defines the mask associated with this state
  8029. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8030. * @param target defines the original target of the state
  8031. * @param currentTarget defines the current target of the state
  8032. */
  8033. function EventState(mask, skipNextObservers, target, currentTarget) {
  8034. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8035. this.initalize(mask, skipNextObservers, target, currentTarget);
  8036. }
  8037. /**
  8038. * Initialize the current event state
  8039. * @param mask defines the mask associated with this state
  8040. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8041. * @param target defines the original target of the state
  8042. * @param currentTarget defines the current target of the state
  8043. * @returns the current event state
  8044. */
  8045. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8046. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8047. this.mask = mask;
  8048. this.skipNextObservers = skipNextObservers;
  8049. this.target = target;
  8050. this.currentTarget = currentTarget;
  8051. return this;
  8052. };
  8053. return EventState;
  8054. }());
  8055. BABYLON.EventState = EventState;
  8056. /**
  8057. * Represent an Observer registered to a given Observable object.
  8058. */
  8059. var Observer = /** @class */ (function () {
  8060. /**
  8061. * Creates a new observer
  8062. * @param callback defines the callback to call when the observer is notified
  8063. * @param mask defines the mask of the observer (used to filter notifications)
  8064. * @param scope defines the current scope used to restore the JS context
  8065. */
  8066. function Observer(
  8067. /**
  8068. * Defines the callback to call when the observer is notified
  8069. */
  8070. callback,
  8071. /**
  8072. * Defines the mask of the observer (used to filter notifications)
  8073. */
  8074. mask,
  8075. /**
  8076. * Defines the current scope used to restore the JS context
  8077. */
  8078. scope) {
  8079. if (scope === void 0) { scope = null; }
  8080. this.callback = callback;
  8081. this.mask = mask;
  8082. this.scope = scope;
  8083. /** @hidden */
  8084. this._willBeUnregistered = false;
  8085. /**
  8086. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8087. */
  8088. this.unregisterOnNextCall = false;
  8089. }
  8090. return Observer;
  8091. }());
  8092. BABYLON.Observer = Observer;
  8093. /**
  8094. * Represent a list of observers registered to multiple Observables object.
  8095. */
  8096. var MultiObserver = /** @class */ (function () {
  8097. function MultiObserver() {
  8098. }
  8099. /**
  8100. * Release associated resources
  8101. */
  8102. MultiObserver.prototype.dispose = function () {
  8103. if (this._observers && this._observables) {
  8104. for (var index = 0; index < this._observers.length; index++) {
  8105. this._observables[index].remove(this._observers[index]);
  8106. }
  8107. }
  8108. this._observers = null;
  8109. this._observables = null;
  8110. };
  8111. /**
  8112. * Raise a callback when one of the observable will notify
  8113. * @param observables defines a list of observables to watch
  8114. * @param callback defines the callback to call on notification
  8115. * @param mask defines the mask used to filter notifications
  8116. * @param scope defines the current scope used to restore the JS context
  8117. * @returns the new MultiObserver
  8118. */
  8119. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8120. if (mask === void 0) { mask = -1; }
  8121. if (scope === void 0) { scope = null; }
  8122. var result = new MultiObserver();
  8123. result._observers = new Array();
  8124. result._observables = observables;
  8125. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8126. var observable = observables_1[_i];
  8127. var observer = observable.add(callback, mask, false, scope);
  8128. if (observer) {
  8129. result._observers.push(observer);
  8130. }
  8131. }
  8132. return result;
  8133. };
  8134. return MultiObserver;
  8135. }());
  8136. BABYLON.MultiObserver = MultiObserver;
  8137. /**
  8138. * The Observable class is a simple implementation of the Observable pattern.
  8139. *
  8140. * 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.
  8141. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8142. * 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).
  8143. * 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.
  8144. */
  8145. var Observable = /** @class */ (function () {
  8146. /**
  8147. * Creates a new observable
  8148. * @param onObserverAdded defines a callback to call when a new observer is added
  8149. */
  8150. function Observable(onObserverAdded) {
  8151. this._observers = new Array();
  8152. this._eventState = new EventState(0);
  8153. if (onObserverAdded) {
  8154. this._onObserverAdded = onObserverAdded;
  8155. }
  8156. }
  8157. /**
  8158. * Create a new Observer with the specified callback
  8159. * @param callback the callback that will be executed for that Observer
  8160. * @param mask the mask used to filter observers
  8161. * @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.
  8162. * @param scope optional scope for the callback to be called from
  8163. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8164. * @returns the new observer created for the callback
  8165. */
  8166. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8167. if (mask === void 0) { mask = -1; }
  8168. if (insertFirst === void 0) { insertFirst = false; }
  8169. if (scope === void 0) { scope = null; }
  8170. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8171. if (!callback) {
  8172. return null;
  8173. }
  8174. var observer = new Observer(callback, mask, scope);
  8175. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8176. if (insertFirst) {
  8177. this._observers.unshift(observer);
  8178. }
  8179. else {
  8180. this._observers.push(observer);
  8181. }
  8182. if (this._onObserverAdded) {
  8183. this._onObserverAdded(observer);
  8184. }
  8185. return observer;
  8186. };
  8187. /**
  8188. * Create a new Observer with the specified callback and unregisters after the next notification
  8189. * @param callback the callback that will be executed for that Observer
  8190. * @returns the new observer created for the callback
  8191. */
  8192. Observable.prototype.addOnce = function (callback) {
  8193. return this.add(callback, undefined, undefined, undefined, true);
  8194. };
  8195. /**
  8196. * Remove an Observer from the Observable object
  8197. * @param observer the instance of the Observer to remove
  8198. * @returns false if it doesn't belong to this Observable
  8199. */
  8200. Observable.prototype.remove = function (observer) {
  8201. if (!observer) {
  8202. return false;
  8203. }
  8204. var index = this._observers.indexOf(observer);
  8205. if (index !== -1) {
  8206. this._observers.splice(index, 1);
  8207. return true;
  8208. }
  8209. return false;
  8210. };
  8211. /**
  8212. * Remove a callback from the Observable object
  8213. * @param callback the callback to remove
  8214. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8215. * @returns false if it doesn't belong to this Observable
  8216. */
  8217. Observable.prototype.removeCallback = function (callback, scope) {
  8218. for (var index = 0; index < this._observers.length; index++) {
  8219. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8220. this._observers.splice(index, 1);
  8221. return true;
  8222. }
  8223. }
  8224. return false;
  8225. };
  8226. Observable.prototype._deferUnregister = function (observer) {
  8227. var _this = this;
  8228. observer.unregisterOnNextCall = false;
  8229. observer._willBeUnregistered = true;
  8230. BABYLON.Tools.SetImmediate(function () {
  8231. _this.remove(observer);
  8232. });
  8233. };
  8234. /**
  8235. * Notify all Observers by calling their respective callback with the given data
  8236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8237. * @param eventData defines the data to send to all observers
  8238. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8239. * @param target defines the original target of the state
  8240. * @param currentTarget defines the current target of the state
  8241. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8242. */
  8243. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8244. if (mask === void 0) { mask = -1; }
  8245. if (!this._observers.length) {
  8246. return true;
  8247. }
  8248. var state = this._eventState;
  8249. state.mask = mask;
  8250. state.target = target;
  8251. state.currentTarget = currentTarget;
  8252. state.skipNextObservers = false;
  8253. state.lastReturnValue = eventData;
  8254. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8255. var obs = _a[_i];
  8256. if (obs._willBeUnregistered) {
  8257. continue;
  8258. }
  8259. if (obs.mask & mask) {
  8260. if (obs.scope) {
  8261. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8262. }
  8263. else {
  8264. state.lastReturnValue = obs.callback(eventData, state);
  8265. }
  8266. if (obs.unregisterOnNextCall) {
  8267. this._deferUnregister(obs);
  8268. }
  8269. }
  8270. if (state.skipNextObservers) {
  8271. return false;
  8272. }
  8273. }
  8274. return true;
  8275. };
  8276. /**
  8277. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8278. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8279. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8280. * and it is crucial that all callbacks will be executed.
  8281. * The order of the callbacks is kept, callbacks are not executed parallel.
  8282. *
  8283. * @param eventData The data to be sent to each callback
  8284. * @param mask is used to filter observers defaults to -1
  8285. * @param target defines the callback target (see EventState)
  8286. * @param currentTarget defines he current object in the bubbling phase
  8287. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8288. */
  8289. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8290. var _this = this;
  8291. if (mask === void 0) { mask = -1; }
  8292. // create an empty promise
  8293. var p = Promise.resolve(eventData);
  8294. // no observers? return this promise.
  8295. if (!this._observers.length) {
  8296. return p;
  8297. }
  8298. var state = this._eventState;
  8299. state.mask = mask;
  8300. state.target = target;
  8301. state.currentTarget = currentTarget;
  8302. state.skipNextObservers = false;
  8303. // execute one callback after another (not using Promise.all, the order is important)
  8304. this._observers.forEach(function (obs) {
  8305. if (state.skipNextObservers) {
  8306. return;
  8307. }
  8308. if (obs._willBeUnregistered) {
  8309. return;
  8310. }
  8311. if (obs.mask & mask) {
  8312. if (obs.scope) {
  8313. p = p.then(function (lastReturnedValue) {
  8314. state.lastReturnValue = lastReturnedValue;
  8315. return obs.callback.apply(obs.scope, [eventData, state]);
  8316. });
  8317. }
  8318. else {
  8319. p = p.then(function (lastReturnedValue) {
  8320. state.lastReturnValue = lastReturnedValue;
  8321. return obs.callback(eventData, state);
  8322. });
  8323. }
  8324. if (obs.unregisterOnNextCall) {
  8325. _this._deferUnregister(obs);
  8326. }
  8327. }
  8328. });
  8329. // return the eventData
  8330. return p.then(function () { return eventData; });
  8331. };
  8332. /**
  8333. * Notify a specific observer
  8334. * @param observer defines the observer to notify
  8335. * @param eventData defines the data to be sent to each callback
  8336. * @param mask is used to filter observers defaults to -1
  8337. */
  8338. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8339. if (mask === void 0) { mask = -1; }
  8340. var state = this._eventState;
  8341. state.mask = mask;
  8342. state.skipNextObservers = false;
  8343. observer.callback(eventData, state);
  8344. };
  8345. /**
  8346. * Gets a boolean indicating if the observable has at least one observer
  8347. * @returns true is the Observable has at least one Observer registered
  8348. */
  8349. Observable.prototype.hasObservers = function () {
  8350. return this._observers.length > 0;
  8351. };
  8352. /**
  8353. * Clear the list of observers
  8354. */
  8355. Observable.prototype.clear = function () {
  8356. this._observers = new Array();
  8357. this._onObserverAdded = null;
  8358. };
  8359. /**
  8360. * Clone the current observable
  8361. * @returns a new observable
  8362. */
  8363. Observable.prototype.clone = function () {
  8364. var result = new Observable();
  8365. result._observers = this._observers.slice(0);
  8366. return result;
  8367. };
  8368. /**
  8369. * Does this observable handles observer registered with a given mask
  8370. * @param mask defines the mask to be tested
  8371. * @return whether or not one observer registered with the given mask is handeled
  8372. **/
  8373. Observable.prototype.hasSpecificMask = function (mask) {
  8374. if (mask === void 0) { mask = -1; }
  8375. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8376. var obs = _a[_i];
  8377. if (obs.mask & mask || obs.mask === mask) {
  8378. return true;
  8379. }
  8380. }
  8381. return false;
  8382. };
  8383. return Observable;
  8384. }());
  8385. BABYLON.Observable = Observable;
  8386. })(BABYLON || (BABYLON = {}));
  8387. //# sourceMappingURL=babylon.observable.js.map
  8388. var BABYLON;
  8389. (function (BABYLON) {
  8390. var SmartArray = /** @class */ (function () {
  8391. function SmartArray(capacity) {
  8392. this.length = 0;
  8393. this.data = new Array(capacity);
  8394. this._id = SmartArray._GlobalId++;
  8395. }
  8396. SmartArray.prototype.push = function (value) {
  8397. this.data[this.length++] = value;
  8398. if (this.length > this.data.length) {
  8399. this.data.length *= 2;
  8400. }
  8401. };
  8402. SmartArray.prototype.forEach = function (func) {
  8403. for (var index = 0; index < this.length; index++) {
  8404. func(this.data[index]);
  8405. }
  8406. };
  8407. SmartArray.prototype.sort = function (compareFn) {
  8408. this.data.sort(compareFn);
  8409. };
  8410. SmartArray.prototype.reset = function () {
  8411. this.length = 0;
  8412. };
  8413. SmartArray.prototype.dispose = function () {
  8414. this.reset();
  8415. if (this.data) {
  8416. this.data.length = 0;
  8417. this.data = [];
  8418. }
  8419. };
  8420. SmartArray.prototype.concat = function (array) {
  8421. if (array.length === 0) {
  8422. return;
  8423. }
  8424. if (this.length + array.length > this.data.length) {
  8425. this.data.length = (this.length + array.length) * 2;
  8426. }
  8427. for (var index = 0; index < array.length; index++) {
  8428. this.data[this.length++] = (array.data || array)[index];
  8429. }
  8430. };
  8431. SmartArray.prototype.indexOf = function (value) {
  8432. var position = this.data.indexOf(value);
  8433. if (position >= this.length) {
  8434. return -1;
  8435. }
  8436. return position;
  8437. };
  8438. SmartArray.prototype.contains = function (value) {
  8439. return this.data.indexOf(value) !== -1;
  8440. };
  8441. // Statics
  8442. SmartArray._GlobalId = 0;
  8443. return SmartArray;
  8444. }());
  8445. BABYLON.SmartArray = SmartArray;
  8446. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8447. __extends(SmartArrayNoDuplicate, _super);
  8448. function SmartArrayNoDuplicate() {
  8449. var _this = _super !== null && _super.apply(this, arguments) || this;
  8450. _this._duplicateId = 0;
  8451. return _this;
  8452. }
  8453. SmartArrayNoDuplicate.prototype.push = function (value) {
  8454. _super.prototype.push.call(this, value);
  8455. if (!value.__smartArrayFlags) {
  8456. value.__smartArrayFlags = {};
  8457. }
  8458. value.__smartArrayFlags[this._id] = this._duplicateId;
  8459. };
  8460. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8461. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8462. return false;
  8463. }
  8464. this.push(value);
  8465. return true;
  8466. };
  8467. SmartArrayNoDuplicate.prototype.reset = function () {
  8468. _super.prototype.reset.call(this);
  8469. this._duplicateId++;
  8470. };
  8471. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8472. if (array.length === 0) {
  8473. return;
  8474. }
  8475. if (this.length + array.length > this.data.length) {
  8476. this.data.length = (this.length + array.length) * 2;
  8477. }
  8478. for (var index = 0; index < array.length; index++) {
  8479. var item = (array.data || array)[index];
  8480. this.pushNoDuplicate(item);
  8481. }
  8482. };
  8483. return SmartArrayNoDuplicate;
  8484. }(SmartArray));
  8485. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8486. })(BABYLON || (BABYLON = {}));
  8487. //# sourceMappingURL=babylon.smartArray.js.map
  8488. var BABYLON;
  8489. (function (BABYLON) {
  8490. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8491. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8492. var LoadFileError = /** @class */ (function (_super) {
  8493. __extends(LoadFileError, _super);
  8494. function LoadFileError(message, request) {
  8495. var _this = _super.call(this, message) || this;
  8496. _this.request = request;
  8497. _this.name = "LoadFileError";
  8498. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8499. return _this;
  8500. }
  8501. // Polyfill for Object.setPrototypeOf if necessary.
  8502. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8503. return LoadFileError;
  8504. }(Error));
  8505. BABYLON.LoadFileError = LoadFileError;
  8506. var RetryStrategy = /** @class */ (function () {
  8507. function RetryStrategy() {
  8508. }
  8509. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8510. if (maxRetries === void 0) { maxRetries = 3; }
  8511. if (baseInterval === void 0) { baseInterval = 500; }
  8512. return function (url, request, retryIndex) {
  8513. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8514. return -1;
  8515. }
  8516. return Math.pow(2, retryIndex) * baseInterval;
  8517. };
  8518. };
  8519. return RetryStrategy;
  8520. }());
  8521. BABYLON.RetryStrategy = RetryStrategy;
  8522. // Screenshots
  8523. var screenshotCanvas;
  8524. var cloneValue = function (source, destinationObject) {
  8525. if (!source)
  8526. return null;
  8527. if (source instanceof BABYLON.Mesh) {
  8528. return null;
  8529. }
  8530. if (source instanceof BABYLON.SubMesh) {
  8531. return source.clone(destinationObject);
  8532. }
  8533. else if (source.clone) {
  8534. return source.clone();
  8535. }
  8536. return null;
  8537. };
  8538. var Tools = /** @class */ (function () {
  8539. function Tools() {
  8540. }
  8541. /**
  8542. * Interpolates between a and b via alpha
  8543. * @param a The lower value (returned when alpha = 0)
  8544. * @param b The upper value (returned when alpha = 1)
  8545. * @param alpha The interpolation-factor
  8546. * @return The mixed value
  8547. */
  8548. Tools.Mix = function (a, b, alpha) {
  8549. return a * (1 - alpha) + b * alpha;
  8550. };
  8551. Tools.Instantiate = function (className) {
  8552. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8553. return Tools.RegisteredExternalClasses[className];
  8554. }
  8555. var arr = className.split(".");
  8556. var fn = (window || this);
  8557. for (var i = 0, len = arr.length; i < len; i++) {
  8558. fn = fn[arr[i]];
  8559. }
  8560. if (typeof fn !== "function") {
  8561. return null;
  8562. }
  8563. return fn;
  8564. };
  8565. /**
  8566. * Provides a slice function that will work even on IE
  8567. * @param data defines the array to slice
  8568. * @param start defines the start of the data (optional)
  8569. * @param end defines the end of the data (optional)
  8570. * @returns the new sliced array
  8571. */
  8572. Tools.Slice = function (data, start, end) {
  8573. if (data.slice) {
  8574. return data.slice(start, end);
  8575. }
  8576. return Array.prototype.slice.call(data, start, end);
  8577. };
  8578. Tools.SetImmediate = function (action) {
  8579. if (window.setImmediate) {
  8580. window.setImmediate(action);
  8581. }
  8582. else {
  8583. setTimeout(action, 1);
  8584. }
  8585. };
  8586. Tools.IsExponentOfTwo = function (value) {
  8587. var count = 1;
  8588. do {
  8589. count *= 2;
  8590. } while (count < value);
  8591. return count === value;
  8592. };
  8593. /**
  8594. * Returns the nearest 32-bit single precision float representation of a Number
  8595. * @param value A Number. If the parameter is of a different type, it will get converted
  8596. * to a number or to NaN if it cannot be converted
  8597. * @returns number
  8598. */
  8599. Tools.FloatRound = function (value) {
  8600. if (Math.fround) {
  8601. return Math.fround(value);
  8602. }
  8603. return (Tools._tmpFloatArray[0] = value);
  8604. };
  8605. /**
  8606. * Find the next highest power of two.
  8607. * @param x Number to start search from.
  8608. * @return Next highest power of two.
  8609. */
  8610. Tools.CeilingPOT = function (x) {
  8611. x--;
  8612. x |= x >> 1;
  8613. x |= x >> 2;
  8614. x |= x >> 4;
  8615. x |= x >> 8;
  8616. x |= x >> 16;
  8617. x++;
  8618. return x;
  8619. };
  8620. /**
  8621. * Find the next lowest power of two.
  8622. * @param x Number to start search from.
  8623. * @return Next lowest power of two.
  8624. */
  8625. Tools.FloorPOT = function (x) {
  8626. x = x | (x >> 1);
  8627. x = x | (x >> 2);
  8628. x = x | (x >> 4);
  8629. x = x | (x >> 8);
  8630. x = x | (x >> 16);
  8631. return x - (x >> 1);
  8632. };
  8633. /**
  8634. * Find the nearest power of two.
  8635. * @param x Number to start search from.
  8636. * @return Next nearest power of two.
  8637. */
  8638. Tools.NearestPOT = function (x) {
  8639. var c = Tools.CeilingPOT(x);
  8640. var f = Tools.FloorPOT(x);
  8641. return (c - x) > (x - f) ? f : c;
  8642. };
  8643. Tools.GetExponentOfTwo = function (value, max, mode) {
  8644. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8645. var pot;
  8646. switch (mode) {
  8647. case BABYLON.Engine.SCALEMODE_FLOOR:
  8648. pot = Tools.FloorPOT(value);
  8649. break;
  8650. case BABYLON.Engine.SCALEMODE_NEAREST:
  8651. pot = Tools.NearestPOT(value);
  8652. break;
  8653. case BABYLON.Engine.SCALEMODE_CEILING:
  8654. default:
  8655. pot = Tools.CeilingPOT(value);
  8656. break;
  8657. }
  8658. return Math.min(pot, max);
  8659. };
  8660. Tools.GetFilename = function (path) {
  8661. var index = path.lastIndexOf("/");
  8662. if (index < 0)
  8663. return path;
  8664. return path.substring(index + 1);
  8665. };
  8666. /**
  8667. * Extracts the "folder" part of a path (everything before the filename).
  8668. * @param uri The URI to extract the info from
  8669. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8670. * @returns The "folder" part of the path
  8671. */
  8672. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8673. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8674. var index = uri.lastIndexOf("/");
  8675. if (index < 0) {
  8676. if (returnUnchangedIfNoSlash) {
  8677. return uri;
  8678. }
  8679. return "";
  8680. }
  8681. return uri.substring(0, index + 1);
  8682. };
  8683. Tools.GetDOMTextContent = function (element) {
  8684. var result = "";
  8685. var child = element.firstChild;
  8686. while (child) {
  8687. if (child.nodeType === 3) {
  8688. result += child.textContent;
  8689. }
  8690. child = child.nextSibling;
  8691. }
  8692. return result;
  8693. };
  8694. Tools.ToDegrees = function (angle) {
  8695. return angle * 180 / Math.PI;
  8696. };
  8697. Tools.ToRadians = function (angle) {
  8698. return angle * Math.PI / 180;
  8699. };
  8700. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8701. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8702. var output = "";
  8703. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8704. var i = 0;
  8705. var bytes = new Uint8Array(buffer);
  8706. while (i < bytes.length) {
  8707. chr1 = bytes[i++];
  8708. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8709. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8710. enc1 = chr1 >> 2;
  8711. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8712. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8713. enc4 = chr3 & 63;
  8714. if (isNaN(chr2)) {
  8715. enc3 = enc4 = 64;
  8716. }
  8717. else if (isNaN(chr3)) {
  8718. enc4 = 64;
  8719. }
  8720. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8721. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8722. }
  8723. return "data:image/png;base64," + output;
  8724. };
  8725. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8726. if (bias === void 0) { bias = null; }
  8727. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8728. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8729. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8730. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8731. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8732. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8733. }
  8734. if (bias) {
  8735. minimum.x -= minimum.x * bias.x + bias.y;
  8736. minimum.y -= minimum.y * bias.x + bias.y;
  8737. minimum.z -= minimum.z * bias.x + bias.y;
  8738. maximum.x += maximum.x * bias.x + bias.y;
  8739. maximum.y += maximum.y * bias.x + bias.y;
  8740. maximum.z += maximum.z * bias.x + bias.y;
  8741. }
  8742. return {
  8743. minimum: minimum,
  8744. maximum: maximum
  8745. };
  8746. };
  8747. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8748. if (bias === void 0) { bias = null; }
  8749. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8750. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8751. if (!stride) {
  8752. stride = 3;
  8753. }
  8754. for (var index = start; index < start + count; index++) {
  8755. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8756. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8757. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8758. }
  8759. if (bias) {
  8760. minimum.x -= minimum.x * bias.x + bias.y;
  8761. minimum.y -= minimum.y * bias.x + bias.y;
  8762. minimum.z -= minimum.z * bias.x + bias.y;
  8763. maximum.x += maximum.x * bias.x + bias.y;
  8764. maximum.y += maximum.y * bias.x + bias.y;
  8765. maximum.z += maximum.z * bias.x + bias.y;
  8766. }
  8767. return {
  8768. minimum: minimum,
  8769. maximum: maximum
  8770. };
  8771. };
  8772. Tools.Vector2ArrayFeeder = function (array) {
  8773. return function (index) {
  8774. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8775. var length = isFloatArray ? array.length / 2 : array.length;
  8776. if (index >= length) {
  8777. return null;
  8778. }
  8779. if (isFloatArray) {
  8780. var fa = array;
  8781. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8782. }
  8783. var a = array;
  8784. return a[index];
  8785. };
  8786. };
  8787. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8788. if (bias === void 0) { bias = null; }
  8789. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8790. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8791. var i = 0;
  8792. var cur = feeder(i++);
  8793. while (cur) {
  8794. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8795. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8796. cur = feeder(i++);
  8797. }
  8798. if (bias) {
  8799. minimum.x -= minimum.x * bias.x + bias.y;
  8800. minimum.y -= minimum.y * bias.x + bias.y;
  8801. maximum.x += maximum.x * bias.x + bias.y;
  8802. maximum.y += maximum.y * bias.x + bias.y;
  8803. }
  8804. return {
  8805. minimum: minimum,
  8806. maximum: maximum
  8807. };
  8808. };
  8809. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8810. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8811. return null;
  8812. return Array.isArray(obj) ? obj : [obj];
  8813. };
  8814. // Misc.
  8815. Tools.GetPointerPrefix = function () {
  8816. var eventPrefix = "pointer";
  8817. // Check if pointer events are supported
  8818. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8819. eventPrefix = "mouse";
  8820. }
  8821. return eventPrefix;
  8822. };
  8823. /**
  8824. * @param func - the function to be called
  8825. * @param requester - the object that will request the next frame. Falls back to window.
  8826. */
  8827. Tools.QueueNewFrame = function (func, requester) {
  8828. if (!Tools.IsWindowObjectExist()) {
  8829. return setTimeout(func, 16);
  8830. }
  8831. if (!requester) {
  8832. requester = window;
  8833. }
  8834. if (requester.requestAnimationFrame) {
  8835. return requester.requestAnimationFrame(func);
  8836. }
  8837. else if (requester.msRequestAnimationFrame) {
  8838. return requester.msRequestAnimationFrame(func);
  8839. }
  8840. else if (requester.webkitRequestAnimationFrame) {
  8841. return requester.webkitRequestAnimationFrame(func);
  8842. }
  8843. else if (requester.mozRequestAnimationFrame) {
  8844. return requester.mozRequestAnimationFrame(func);
  8845. }
  8846. else if (requester.oRequestAnimationFrame) {
  8847. return requester.oRequestAnimationFrame(func);
  8848. }
  8849. else {
  8850. return window.setTimeout(func, 16);
  8851. }
  8852. };
  8853. Tools.RequestFullscreen = function (element) {
  8854. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8855. if (!requestFunction)
  8856. return;
  8857. requestFunction.call(element);
  8858. };
  8859. Tools.ExitFullscreen = function () {
  8860. if (document.exitFullscreen) {
  8861. document.exitFullscreen();
  8862. }
  8863. else if (document.mozCancelFullScreen) {
  8864. document.mozCancelFullScreen();
  8865. }
  8866. else if (document.webkitCancelFullScreen) {
  8867. document.webkitCancelFullScreen();
  8868. }
  8869. else if (document.msCancelFullScreen) {
  8870. document.msCancelFullScreen();
  8871. }
  8872. };
  8873. Tools.SetCorsBehavior = function (url, element) {
  8874. if (url && url.indexOf("data:") === 0) {
  8875. return;
  8876. }
  8877. if (Tools.CorsBehavior) {
  8878. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8879. element.crossOrigin = Tools.CorsBehavior;
  8880. }
  8881. else {
  8882. var result = Tools.CorsBehavior(url);
  8883. if (result) {
  8884. element.crossOrigin = result;
  8885. }
  8886. }
  8887. }
  8888. };
  8889. // External files
  8890. Tools.CleanUrl = function (url) {
  8891. url = url.replace(/#/mg, "%23");
  8892. return url;
  8893. };
  8894. /**
  8895. * Loads an image as an HTMLImageElement.
  8896. * @param input url string, ArrayBuffer, or Blob to load
  8897. * @param onLoad callback called when the image successfully loads
  8898. * @param onError callback called when the image fails to load
  8899. * @param database database for caching
  8900. * @returns the HTMLImageElement of the loaded image
  8901. */
  8902. Tools.LoadImage = function (input, onLoad, onError, database) {
  8903. var url;
  8904. var usingObjectURL = false;
  8905. if (input instanceof ArrayBuffer) {
  8906. url = URL.createObjectURL(new Blob([input]));
  8907. usingObjectURL = true;
  8908. }
  8909. else if (input instanceof Blob) {
  8910. url = URL.createObjectURL(input);
  8911. usingObjectURL = true;
  8912. }
  8913. else {
  8914. url = Tools.CleanUrl(input);
  8915. url = Tools.PreprocessUrl(input);
  8916. }
  8917. var img = new Image();
  8918. Tools.SetCorsBehavior(url, img);
  8919. var loadHandler = function () {
  8920. if (usingObjectURL && img.src) {
  8921. URL.revokeObjectURL(img.src);
  8922. }
  8923. img.removeEventListener("load", loadHandler);
  8924. img.removeEventListener("error", errorHandler);
  8925. onLoad(img);
  8926. };
  8927. var errorHandler = function (err) {
  8928. if (usingObjectURL && img.src) {
  8929. URL.revokeObjectURL(img.src);
  8930. }
  8931. img.removeEventListener("load", loadHandler);
  8932. img.removeEventListener("error", errorHandler);
  8933. Tools.Error("Error while trying to load image: " + input);
  8934. if (onError) {
  8935. onError("Error while trying to load image: " + input, err);
  8936. }
  8937. };
  8938. img.addEventListener("load", loadHandler);
  8939. img.addEventListener("error", errorHandler);
  8940. var noIndexedDB = function () {
  8941. img.src = url;
  8942. };
  8943. var loadFromIndexedDB = function () {
  8944. if (database) {
  8945. database.loadImageFromDB(url, img);
  8946. }
  8947. };
  8948. //ANY database to do!
  8949. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8950. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8951. }
  8952. else {
  8953. if (url.indexOf("file:") !== -1) {
  8954. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8955. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8956. try {
  8957. var blobURL;
  8958. try {
  8959. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8960. }
  8961. catch (ex) {
  8962. // Chrome doesn't support oneTimeOnly parameter
  8963. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8964. }
  8965. img.src = blobURL;
  8966. usingObjectURL = true;
  8967. }
  8968. catch (e) {
  8969. img.src = "";
  8970. }
  8971. return img;
  8972. }
  8973. }
  8974. noIndexedDB();
  8975. }
  8976. return img;
  8977. };
  8978. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8979. url = Tools.CleanUrl(url);
  8980. url = Tools.PreprocessUrl(url);
  8981. // If file and file input are set
  8982. if (url.indexOf("file:") !== -1) {
  8983. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8984. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8985. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8986. }
  8987. }
  8988. var loadUrl = Tools.BaseUrl + url;
  8989. var aborted = false;
  8990. var fileRequest = {
  8991. onCompleteObservable: new BABYLON.Observable(),
  8992. abort: function () { return aborted = true; },
  8993. };
  8994. var requestFile = function () {
  8995. var request = new XMLHttpRequest();
  8996. var retryHandle = null;
  8997. fileRequest.abort = function () {
  8998. aborted = true;
  8999. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9000. request.abort();
  9001. }
  9002. if (retryHandle !== null) {
  9003. clearTimeout(retryHandle);
  9004. retryHandle = null;
  9005. }
  9006. };
  9007. var retryLoop = function (retryIndex) {
  9008. request.open('GET', loadUrl, true);
  9009. if (useArrayBuffer) {
  9010. request.responseType = "arraybuffer";
  9011. }
  9012. if (onProgress) {
  9013. request.addEventListener("progress", onProgress);
  9014. }
  9015. var onLoadEnd = function () {
  9016. request.removeEventListener("loadend", onLoadEnd);
  9017. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9018. fileRequest.onCompleteObservable.clear();
  9019. };
  9020. request.addEventListener("loadend", onLoadEnd);
  9021. var onReadyStateChange = function () {
  9022. if (aborted) {
  9023. return;
  9024. }
  9025. // In case of undefined state in some browsers.
  9026. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9027. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9028. request.removeEventListener("readystatechange", onReadyStateChange);
  9029. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9030. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9031. return;
  9032. }
  9033. var retryStrategy = Tools.DefaultRetryStrategy;
  9034. if (retryStrategy) {
  9035. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9036. if (waitTime !== -1) {
  9037. // Prevent the request from completing for retry.
  9038. request.removeEventListener("loadend", onLoadEnd);
  9039. request = new XMLHttpRequest();
  9040. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9041. return;
  9042. }
  9043. }
  9044. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9045. if (onError) {
  9046. onError(request, e);
  9047. }
  9048. else {
  9049. throw e;
  9050. }
  9051. }
  9052. };
  9053. request.addEventListener("readystatechange", onReadyStateChange);
  9054. request.send();
  9055. };
  9056. retryLoop(0);
  9057. };
  9058. // Caching all files
  9059. if (database && database.enableSceneOffline) {
  9060. var noIndexedDB_1 = function () {
  9061. if (!aborted) {
  9062. requestFile();
  9063. }
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. // TODO: database needs to support aborting and should return a IFileRequest
  9067. if (aborted) {
  9068. return;
  9069. }
  9070. if (database) {
  9071. database.loadFileFromDB(url, function (data) {
  9072. if (!aborted) {
  9073. onSuccess(data);
  9074. }
  9075. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9076. }, onProgress ? function (event) {
  9077. if (!aborted) {
  9078. onProgress(event);
  9079. }
  9080. } : undefined, noIndexedDB_1, useArrayBuffer);
  9081. }
  9082. };
  9083. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9084. }
  9085. else {
  9086. requestFile();
  9087. }
  9088. return fileRequest;
  9089. };
  9090. /**
  9091. * Load a script (identified by an url). When the url returns, the
  9092. * content of this file is added into a new script element, attached to the DOM (body element)
  9093. */
  9094. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9095. var head = document.getElementsByTagName('head')[0];
  9096. var script = document.createElement('script');
  9097. script.type = 'text/javascript';
  9098. script.src = scriptUrl;
  9099. script.onload = function () {
  9100. if (onSuccess) {
  9101. onSuccess();
  9102. }
  9103. };
  9104. script.onerror = function (e) {
  9105. if (onError) {
  9106. onError("Unable to load script '" + scriptUrl + "'", e);
  9107. }
  9108. };
  9109. head.appendChild(script);
  9110. };
  9111. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9112. var reader = new FileReader();
  9113. var request = {
  9114. onCompleteObservable: new BABYLON.Observable(),
  9115. abort: function () { return reader.abort(); },
  9116. };
  9117. reader.onloadend = function (e) {
  9118. request.onCompleteObservable.notifyObservers(request);
  9119. };
  9120. reader.onload = function (e) {
  9121. //target doesn't have result from ts 1.3
  9122. callback(e.target['result']);
  9123. };
  9124. reader.onprogress = progressCallback;
  9125. reader.readAsDataURL(fileToLoad);
  9126. return request;
  9127. };
  9128. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9129. var reader = new FileReader();
  9130. var request = {
  9131. onCompleteObservable: new BABYLON.Observable(),
  9132. abort: function () { return reader.abort(); },
  9133. };
  9134. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9135. reader.onerror = function (e) {
  9136. Tools.Log("Error while reading file: " + fileToLoad.name);
  9137. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9138. };
  9139. reader.onload = function (e) {
  9140. //target doesn't have result from ts 1.3
  9141. callback(e.target['result']);
  9142. };
  9143. if (progressCallBack) {
  9144. reader.onprogress = progressCallBack;
  9145. }
  9146. if (!useArrayBuffer) {
  9147. // Asynchronous read
  9148. reader.readAsText(fileToLoad);
  9149. }
  9150. else {
  9151. reader.readAsArrayBuffer(fileToLoad);
  9152. }
  9153. return request;
  9154. };
  9155. //returns a downloadable url to a file content.
  9156. Tools.FileAsURL = function (content) {
  9157. var fileBlob = new Blob([content]);
  9158. var url = window.URL || window.webkitURL;
  9159. var link = url.createObjectURL(fileBlob);
  9160. return link;
  9161. };
  9162. // Misc.
  9163. Tools.Format = function (value, decimals) {
  9164. if (decimals === void 0) { decimals = 2; }
  9165. return value.toFixed(decimals);
  9166. };
  9167. Tools.CheckExtends = function (v, min, max) {
  9168. if (v.x < min.x)
  9169. min.x = v.x;
  9170. if (v.y < min.y)
  9171. min.y = v.y;
  9172. if (v.z < min.z)
  9173. min.z = v.z;
  9174. if (v.x > max.x)
  9175. max.x = v.x;
  9176. if (v.y > max.y)
  9177. max.y = v.y;
  9178. if (v.z > max.z)
  9179. max.z = v.z;
  9180. };
  9181. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9182. for (var prop in source) {
  9183. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9184. continue;
  9185. }
  9186. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9187. continue;
  9188. }
  9189. var sourceValue = source[prop];
  9190. var typeOfSourceValue = typeof sourceValue;
  9191. if (typeOfSourceValue === "function") {
  9192. continue;
  9193. }
  9194. try {
  9195. if (typeOfSourceValue === "object") {
  9196. if (sourceValue instanceof Array) {
  9197. destination[prop] = [];
  9198. if (sourceValue.length > 0) {
  9199. if (typeof sourceValue[0] == "object") {
  9200. for (var index = 0; index < sourceValue.length; index++) {
  9201. var clonedValue = cloneValue(sourceValue[index], destination);
  9202. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9203. destination[prop].push(clonedValue);
  9204. }
  9205. }
  9206. }
  9207. else {
  9208. destination[prop] = sourceValue.slice(0);
  9209. }
  9210. }
  9211. }
  9212. else {
  9213. destination[prop] = cloneValue(sourceValue, destination);
  9214. }
  9215. }
  9216. else {
  9217. destination[prop] = sourceValue;
  9218. }
  9219. }
  9220. catch (e) {
  9221. // Just ignore error (it could be because of a read-only property)
  9222. }
  9223. }
  9224. };
  9225. Tools.IsEmpty = function (obj) {
  9226. for (var i in obj) {
  9227. if (obj.hasOwnProperty(i)) {
  9228. return false;
  9229. }
  9230. }
  9231. return true;
  9232. };
  9233. Tools.RegisterTopRootEvents = function (events) {
  9234. for (var index = 0; index < events.length; index++) {
  9235. var event = events[index];
  9236. window.addEventListener(event.name, event.handler, false);
  9237. try {
  9238. if (window.parent) {
  9239. window.parent.addEventListener(event.name, event.handler, false);
  9240. }
  9241. }
  9242. catch (e) {
  9243. // Silently fails...
  9244. }
  9245. }
  9246. };
  9247. Tools.UnregisterTopRootEvents = function (events) {
  9248. for (var index = 0; index < events.length; index++) {
  9249. var event = events[index];
  9250. window.removeEventListener(event.name, event.handler);
  9251. try {
  9252. if (window.parent) {
  9253. window.parent.removeEventListener(event.name, event.handler);
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Silently fails...
  9258. }
  9259. }
  9260. };
  9261. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9262. if (mimeType === void 0) { mimeType = "image/png"; }
  9263. // Read the contents of the framebuffer
  9264. var numberOfChannelsByLine = width * 4;
  9265. var halfHeight = height / 2;
  9266. //Reading datas from WebGL
  9267. var data = engine.readPixels(0, 0, width, height);
  9268. //To flip image on Y axis.
  9269. for (var i = 0; i < halfHeight; i++) {
  9270. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9271. var currentCell = j + i * numberOfChannelsByLine;
  9272. var targetLine = height - i - 1;
  9273. var targetCell = j + targetLine * numberOfChannelsByLine;
  9274. var temp = data[currentCell];
  9275. data[currentCell] = data[targetCell];
  9276. data[targetCell] = temp;
  9277. }
  9278. }
  9279. // Create a 2D canvas to store the result
  9280. if (!screenshotCanvas) {
  9281. screenshotCanvas = document.createElement('canvas');
  9282. }
  9283. screenshotCanvas.width = width;
  9284. screenshotCanvas.height = height;
  9285. var context = screenshotCanvas.getContext('2d');
  9286. if (context) {
  9287. // Copy the pixels to a 2D canvas
  9288. var imageData = context.createImageData(width, height);
  9289. var castData = (imageData.data);
  9290. castData.set(data);
  9291. context.putImageData(imageData, 0, 0);
  9292. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9293. }
  9294. };
  9295. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9296. if (mimeType === void 0) { mimeType = "image/png"; }
  9297. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9298. if (successCallback) {
  9299. successCallback(base64Image);
  9300. }
  9301. else {
  9302. // We need HTMLCanvasElement.toBlob for HD screenshots
  9303. if (!screenshotCanvas.toBlob) {
  9304. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9305. screenshotCanvas.toBlob = function (callback, type, quality) {
  9306. var _this = this;
  9307. setTimeout(function () {
  9308. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9309. for (var i = 0; i < len; i++) {
  9310. arr[i] = binStr.charCodeAt(i);
  9311. }
  9312. callback(new Blob([arr], { type: type || 'image/png' }));
  9313. });
  9314. };
  9315. }
  9316. screenshotCanvas.toBlob(function (blob) {
  9317. var url = URL.createObjectURL(blob);
  9318. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9319. if (("download" in document.createElement("a"))) {
  9320. var a = window.document.createElement("a");
  9321. a.href = url;
  9322. if (fileName) {
  9323. a.setAttribute("download", fileName);
  9324. }
  9325. else {
  9326. var date = new Date();
  9327. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9328. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9329. }
  9330. window.document.body.appendChild(a);
  9331. a.addEventListener("click", function () {
  9332. if (a.parentElement) {
  9333. a.parentElement.removeChild(a);
  9334. }
  9335. });
  9336. a.click();
  9337. }
  9338. else {
  9339. var newWindow = window.open("");
  9340. if (!newWindow)
  9341. return;
  9342. var img = newWindow.document.createElement("img");
  9343. img.onload = function () {
  9344. // no longer need to read the blob so it's revoked
  9345. URL.revokeObjectURL(url);
  9346. };
  9347. img.src = url;
  9348. newWindow.document.body.appendChild(img);
  9349. }
  9350. });
  9351. }
  9352. };
  9353. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9354. if (mimeType === void 0) { mimeType = "image/png"; }
  9355. var width;
  9356. var height;
  9357. // If a precision value is specified
  9358. if (size.precision) {
  9359. width = Math.round(engine.getRenderWidth() * size.precision);
  9360. height = Math.round(width / engine.getAspectRatio(camera));
  9361. }
  9362. else if (size.width && size.height) {
  9363. width = size.width;
  9364. height = size.height;
  9365. }
  9366. //If passing only width, computing height to keep display canvas ratio.
  9367. else if (size.width && !size.height) {
  9368. width = size.width;
  9369. height = Math.round(width / engine.getAspectRatio(camera));
  9370. }
  9371. //If passing only height, computing width to keep display canvas ratio.
  9372. else if (size.height && !size.width) {
  9373. height = size.height;
  9374. width = Math.round(height * engine.getAspectRatio(camera));
  9375. }
  9376. //Assuming here that "size" parameter is a number
  9377. else if (!isNaN(size)) {
  9378. height = size;
  9379. width = size;
  9380. }
  9381. else {
  9382. Tools.Error("Invalid 'size' parameter !");
  9383. return;
  9384. }
  9385. if (!screenshotCanvas) {
  9386. screenshotCanvas = document.createElement('canvas');
  9387. }
  9388. screenshotCanvas.width = width;
  9389. screenshotCanvas.height = height;
  9390. var renderContext = screenshotCanvas.getContext("2d");
  9391. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9392. var newWidth = width;
  9393. var newHeight = newWidth / ratio;
  9394. if (newHeight > height) {
  9395. newHeight = height;
  9396. newWidth = newHeight * ratio;
  9397. }
  9398. var offsetX = Math.max(0, width - newWidth) / 2;
  9399. var offsetY = Math.max(0, height - newHeight) / 2;
  9400. var renderingCanvas = engine.getRenderingCanvas();
  9401. if (renderContext && renderingCanvas) {
  9402. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9403. }
  9404. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9405. };
  9406. /**
  9407. * Generates an image screenshot from the specified camera.
  9408. *
  9409. * @param engine The engine to use for rendering
  9410. * @param camera The camera to use for rendering
  9411. * @param size This parameter can be set to a single number or to an object with the
  9412. * following (optional) properties: precision, width, height. If a single number is passed,
  9413. * it will be used for both width and height. If an object is passed, the screenshot size
  9414. * will be derived from the parameters. The precision property is a multiplier allowing
  9415. * rendering at a higher or lower resolution.
  9416. * @param successCallback The callback receives a single parameter which contains the
  9417. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9418. * src parameter of an <img> to display it.
  9419. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9420. * Check your browser for supported MIME types.
  9421. * @param samples Texture samples (default: 1)
  9422. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9423. * @param fileName A name for for the downloaded file.
  9424. * @constructor
  9425. */
  9426. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9427. if (mimeType === void 0) { mimeType = "image/png"; }
  9428. if (samples === void 0) { samples = 1; }
  9429. if (antialiasing === void 0) { antialiasing = false; }
  9430. var width;
  9431. var height;
  9432. //If a precision value is specified
  9433. if (size.precision) {
  9434. width = Math.round(engine.getRenderWidth() * size.precision);
  9435. height = Math.round(width / engine.getAspectRatio(camera));
  9436. size = { width: width, height: height };
  9437. }
  9438. else if (size.width && size.height) {
  9439. width = size.width;
  9440. height = size.height;
  9441. }
  9442. //If passing only width, computing height to keep display canvas ratio.
  9443. else if (size.width && !size.height) {
  9444. width = size.width;
  9445. height = Math.round(width / engine.getAspectRatio(camera));
  9446. size = { width: width, height: height };
  9447. }
  9448. //If passing only height, computing width to keep display canvas ratio.
  9449. else if (size.height && !size.width) {
  9450. height = size.height;
  9451. width = Math.round(height * engine.getAspectRatio(camera));
  9452. size = { width: width, height: height };
  9453. }
  9454. //Assuming here that "size" parameter is a number
  9455. else if (!isNaN(size)) {
  9456. height = size;
  9457. width = size;
  9458. }
  9459. else {
  9460. Tools.Error("Invalid 'size' parameter !");
  9461. return;
  9462. }
  9463. var scene = camera.getScene();
  9464. var previousCamera = null;
  9465. if (scene.activeCamera !== camera) {
  9466. previousCamera = scene.activeCamera;
  9467. scene.activeCamera = camera;
  9468. }
  9469. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9470. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9471. texture.renderList = null;
  9472. texture.samples = samples;
  9473. if (antialiasing) {
  9474. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9475. }
  9476. texture.onAfterRenderObservable.add(function () {
  9477. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9478. });
  9479. scene.incrementRenderId();
  9480. scene.resetCachedMaterial();
  9481. texture.render(true);
  9482. texture.dispose();
  9483. if (previousCamera) {
  9484. scene.activeCamera = previousCamera;
  9485. }
  9486. camera.getProjectionMatrix(true); // Force cache refresh;
  9487. };
  9488. // XHR response validator for local file scenario
  9489. Tools.ValidateXHRData = function (xhr, dataType) {
  9490. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9491. if (dataType === void 0) { dataType = 7; }
  9492. try {
  9493. if (dataType & 1) {
  9494. if (xhr.responseText && xhr.responseText.length > 0) {
  9495. return true;
  9496. }
  9497. else if (dataType === 1) {
  9498. return false;
  9499. }
  9500. }
  9501. if (dataType & 2) {
  9502. // Check header width and height since there is no "TGA" magic number
  9503. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9504. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9505. return true;
  9506. }
  9507. else if (dataType === 2) {
  9508. return false;
  9509. }
  9510. }
  9511. if (dataType & 4) {
  9512. // Check for the "DDS" magic number
  9513. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9514. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9515. return true;
  9516. }
  9517. else {
  9518. return false;
  9519. }
  9520. }
  9521. }
  9522. catch (e) {
  9523. // Global protection
  9524. }
  9525. return false;
  9526. };
  9527. /**
  9528. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9529. * Be aware Math.random() could cause collisions, but:
  9530. * "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"
  9531. */
  9532. Tools.RandomId = function () {
  9533. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9534. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9535. return v.toString(16);
  9536. });
  9537. };
  9538. /**
  9539. * Test if the given uri is a base64 string.
  9540. * @param uri The uri to test
  9541. * @return True if the uri is a base64 string or false otherwise.
  9542. */
  9543. Tools.IsBase64 = function (uri) {
  9544. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9545. };
  9546. /**
  9547. * Decode the given base64 uri.
  9548. * @param uri The uri to decode
  9549. * @return The decoded base64 data.
  9550. */
  9551. Tools.DecodeBase64 = function (uri) {
  9552. var decodedString = atob(uri.split(",")[1]);
  9553. var bufferLength = decodedString.length;
  9554. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9555. for (var i = 0; i < bufferLength; i++) {
  9556. bufferView[i] = decodedString.charCodeAt(i);
  9557. }
  9558. return bufferView.buffer;
  9559. };
  9560. Object.defineProperty(Tools, "NoneLogLevel", {
  9561. get: function () {
  9562. return Tools._NoneLogLevel;
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. Object.defineProperty(Tools, "MessageLogLevel", {
  9568. get: function () {
  9569. return Tools._MessageLogLevel;
  9570. },
  9571. enumerable: true,
  9572. configurable: true
  9573. });
  9574. Object.defineProperty(Tools, "WarningLogLevel", {
  9575. get: function () {
  9576. return Tools._WarningLogLevel;
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Object.defineProperty(Tools, "ErrorLogLevel", {
  9582. get: function () {
  9583. return Tools._ErrorLogLevel;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(Tools, "AllLogLevel", {
  9589. get: function () {
  9590. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Tools._AddLogEntry = function (entry) {
  9596. Tools._LogCache = entry + Tools._LogCache;
  9597. if (Tools.OnNewCacheEntry) {
  9598. Tools.OnNewCacheEntry(entry);
  9599. }
  9600. };
  9601. Tools._FormatMessage = function (message) {
  9602. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9603. var date = new Date();
  9604. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9605. };
  9606. Tools._LogDisabled = function (message) {
  9607. // nothing to do
  9608. };
  9609. Tools._LogEnabled = function (message) {
  9610. var formattedMessage = Tools._FormatMessage(message);
  9611. console.log("BJS - " + formattedMessage);
  9612. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9613. Tools._AddLogEntry(entry);
  9614. };
  9615. Tools._WarnDisabled = function (message) {
  9616. // nothing to do
  9617. };
  9618. Tools._WarnEnabled = function (message) {
  9619. var formattedMessage = Tools._FormatMessage(message);
  9620. console.warn("BJS - " + formattedMessage);
  9621. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9622. Tools._AddLogEntry(entry);
  9623. };
  9624. Tools._ErrorDisabled = function (message) {
  9625. // nothing to do
  9626. };
  9627. Tools._ErrorEnabled = function (message) {
  9628. Tools.errorsCount++;
  9629. var formattedMessage = Tools._FormatMessage(message);
  9630. console.error("BJS - " + formattedMessage);
  9631. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9632. Tools._AddLogEntry(entry);
  9633. };
  9634. Object.defineProperty(Tools, "LogCache", {
  9635. get: function () {
  9636. return Tools._LogCache;
  9637. },
  9638. enumerable: true,
  9639. configurable: true
  9640. });
  9641. Tools.ClearLogCache = function () {
  9642. Tools._LogCache = "";
  9643. Tools.errorsCount = 0;
  9644. };
  9645. Object.defineProperty(Tools, "LogLevels", {
  9646. set: function (level) {
  9647. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9648. Tools.Log = Tools._LogEnabled;
  9649. }
  9650. else {
  9651. Tools.Log = Tools._LogDisabled;
  9652. }
  9653. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9654. Tools.Warn = Tools._WarnEnabled;
  9655. }
  9656. else {
  9657. Tools.Warn = Tools._WarnDisabled;
  9658. }
  9659. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9660. Tools.Error = Tools._ErrorEnabled;
  9661. }
  9662. else {
  9663. Tools.Error = Tools._ErrorDisabled;
  9664. }
  9665. },
  9666. enumerable: true,
  9667. configurable: true
  9668. });
  9669. Tools.IsWindowObjectExist = function () {
  9670. return (typeof window) !== "undefined";
  9671. };
  9672. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9673. get: function () {
  9674. return Tools._PerformanceNoneLogLevel;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9680. get: function () {
  9681. return Tools._PerformanceUserMarkLogLevel;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9687. get: function () {
  9688. return Tools._PerformanceConsoleLogLevel;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9694. set: function (level) {
  9695. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9696. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9697. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9698. return;
  9699. }
  9700. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9701. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9702. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9703. return;
  9704. }
  9705. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9706. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9707. },
  9708. enumerable: true,
  9709. configurable: true
  9710. });
  9711. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9712. };
  9713. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9714. };
  9715. Tools._StartUserMark = function (counterName, condition) {
  9716. if (condition === void 0) { condition = true; }
  9717. if (!Tools._performance) {
  9718. if (!Tools.IsWindowObjectExist()) {
  9719. return;
  9720. }
  9721. Tools._performance = window.performance;
  9722. }
  9723. if (!condition || !Tools._performance.mark) {
  9724. return;
  9725. }
  9726. Tools._performance.mark(counterName + "-Begin");
  9727. };
  9728. Tools._EndUserMark = function (counterName, condition) {
  9729. if (condition === void 0) { condition = true; }
  9730. if (!condition || !Tools._performance.mark) {
  9731. return;
  9732. }
  9733. Tools._performance.mark(counterName + "-End");
  9734. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9735. };
  9736. Tools._StartPerformanceConsole = function (counterName, condition) {
  9737. if (condition === void 0) { condition = true; }
  9738. if (!condition) {
  9739. return;
  9740. }
  9741. Tools._StartUserMark(counterName, condition);
  9742. if (console.time) {
  9743. console.time(counterName);
  9744. }
  9745. };
  9746. Tools._EndPerformanceConsole = function (counterName, condition) {
  9747. if (condition === void 0) { condition = true; }
  9748. if (!condition) {
  9749. return;
  9750. }
  9751. Tools._EndUserMark(counterName, condition);
  9752. if (console.time) {
  9753. console.timeEnd(counterName);
  9754. }
  9755. };
  9756. Object.defineProperty(Tools, "Now", {
  9757. get: function () {
  9758. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9759. return window.performance.now();
  9760. }
  9761. return Date.now();
  9762. },
  9763. enumerable: true,
  9764. configurable: true
  9765. });
  9766. /**
  9767. * This method will return the name of the class used to create the instance of the given object.
  9768. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9769. * @param object the object to get the class name from
  9770. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9771. */
  9772. Tools.GetClassName = function (object, isType) {
  9773. if (isType === void 0) { isType = false; }
  9774. var name = null;
  9775. if (!isType && object.getClassName) {
  9776. name = object.getClassName();
  9777. }
  9778. else {
  9779. if (object instanceof Object) {
  9780. var classObj = isType ? object : Object.getPrototypeOf(object);
  9781. name = classObj.constructor["__bjsclassName__"];
  9782. }
  9783. if (!name) {
  9784. name = typeof object;
  9785. }
  9786. }
  9787. return name;
  9788. };
  9789. Tools.First = function (array, predicate) {
  9790. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9791. var el = array_1[_i];
  9792. if (predicate(el)) {
  9793. return el;
  9794. }
  9795. }
  9796. return null;
  9797. };
  9798. /**
  9799. * This method will return the name of the full name of the class, including its owning module (if any).
  9800. * 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).
  9801. * @param object the object to get the class name from
  9802. * @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.
  9803. */
  9804. Tools.getFullClassName = function (object, isType) {
  9805. if (isType === void 0) { isType = false; }
  9806. var className = null;
  9807. var moduleName = null;
  9808. if (!isType && object.getClassName) {
  9809. className = object.getClassName();
  9810. }
  9811. else {
  9812. if (object instanceof Object) {
  9813. var classObj = isType ? object : Object.getPrototypeOf(object);
  9814. className = classObj.constructor["__bjsclassName__"];
  9815. moduleName = classObj.constructor["__bjsmoduleName__"];
  9816. }
  9817. if (!className) {
  9818. className = typeof object;
  9819. }
  9820. }
  9821. if (!className) {
  9822. return null;
  9823. }
  9824. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9825. };
  9826. /**
  9827. * 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.
  9828. * @param array
  9829. */
  9830. Tools.arrayOrStringFeeder = function (array) {
  9831. return function (index) {
  9832. if (index >= array.length) {
  9833. return null;
  9834. }
  9835. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9836. if (val && val.getHashCode) {
  9837. val = val.getHashCode();
  9838. }
  9839. if (typeof val === "string") {
  9840. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9841. }
  9842. return val;
  9843. };
  9844. };
  9845. /**
  9846. * Compute the hashCode of a stream of number
  9847. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9848. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9849. * @return the hash code computed
  9850. */
  9851. Tools.hashCodeFromStream = function (feeder) {
  9852. // Based from here: http://stackoverflow.com/a/7616484/802124
  9853. var hash = 0;
  9854. var index = 0;
  9855. var chr = feeder(index++);
  9856. while (chr != null) {
  9857. hash = ((hash << 5) - hash) + chr;
  9858. hash |= 0; // Convert to 32bit integer
  9859. chr = feeder(index++);
  9860. }
  9861. return hash;
  9862. };
  9863. /**
  9864. * Returns a promise that resolves after the given amount of time.
  9865. * @param delay Number of milliseconds to delay
  9866. * @returns Promise that resolves after the given amount of time
  9867. */
  9868. Tools.DelayAsync = function (delay) {
  9869. return new Promise(function (resolve) {
  9870. setTimeout(function () {
  9871. resolve();
  9872. }, delay);
  9873. });
  9874. };
  9875. Tools.BaseUrl = "";
  9876. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9877. /**
  9878. * Default behaviour for cors in the application.
  9879. * It can be a string if the expected behavior is identical in the entire app.
  9880. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9881. */
  9882. Tools.CorsBehavior = "anonymous";
  9883. Tools.UseFallbackTexture = true;
  9884. /**
  9885. * Use this object to register external classes like custom textures or material
  9886. * to allow the laoders to instantiate them
  9887. */
  9888. Tools.RegisteredExternalClasses = {};
  9889. // Used in case of a texture loading problem
  9890. 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";
  9891. Tools._tmpFloatArray = new Float32Array(1);
  9892. Tools.PreprocessUrl = function (url) {
  9893. return url;
  9894. };
  9895. // Logs
  9896. Tools._NoneLogLevel = 0;
  9897. Tools._MessageLogLevel = 1;
  9898. Tools._WarningLogLevel = 2;
  9899. Tools._ErrorLogLevel = 4;
  9900. Tools._LogCache = "";
  9901. Tools.errorsCount = 0;
  9902. Tools.Log = Tools._LogEnabled;
  9903. Tools.Warn = Tools._WarnEnabled;
  9904. Tools.Error = Tools._ErrorEnabled;
  9905. // Performances
  9906. Tools._PerformanceNoneLogLevel = 0;
  9907. Tools._PerformanceUserMarkLogLevel = 1;
  9908. Tools._PerformanceConsoleLogLevel = 2;
  9909. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9910. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9911. return Tools;
  9912. }());
  9913. BABYLON.Tools = Tools;
  9914. /**
  9915. * This class is used to track a performance counter which is number based.
  9916. * The user has access to many properties which give statistics of different nature
  9917. *
  9918. * The implementer can track two kinds of Performance Counter: time and count
  9919. * 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.
  9920. * 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.
  9921. */
  9922. var PerfCounter = /** @class */ (function () {
  9923. function PerfCounter() {
  9924. this._startMonitoringTime = 0;
  9925. this._min = 0;
  9926. this._max = 0;
  9927. this._average = 0;
  9928. this._lastSecAverage = 0;
  9929. this._current = 0;
  9930. this._totalValueCount = 0;
  9931. this._totalAccumulated = 0;
  9932. this._lastSecAccumulated = 0;
  9933. this._lastSecTime = 0;
  9934. this._lastSecValueCount = 0;
  9935. }
  9936. Object.defineProperty(PerfCounter.prototype, "min", {
  9937. /**
  9938. * Returns the smallest value ever
  9939. */
  9940. get: function () {
  9941. return this._min;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(PerfCounter.prototype, "max", {
  9947. /**
  9948. * Returns the biggest value ever
  9949. */
  9950. get: function () {
  9951. return this._max;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(PerfCounter.prototype, "average", {
  9957. /**
  9958. * Returns the average value since the performance counter is running
  9959. */
  9960. get: function () {
  9961. return this._average;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9967. /**
  9968. * Returns the average value of the last second the counter was monitored
  9969. */
  9970. get: function () {
  9971. return this._lastSecAverage;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(PerfCounter.prototype, "current", {
  9977. /**
  9978. * Returns the current value
  9979. */
  9980. get: function () {
  9981. return this._current;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(PerfCounter.prototype, "total", {
  9987. get: function () {
  9988. return this._totalAccumulated;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. Object.defineProperty(PerfCounter.prototype, "count", {
  9994. get: function () {
  9995. return this._totalValueCount;
  9996. },
  9997. enumerable: true,
  9998. configurable: true
  9999. });
  10000. /**
  10001. * Call this method to start monitoring a new frame.
  10002. * 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.
  10003. */
  10004. PerfCounter.prototype.fetchNewFrame = function () {
  10005. this._totalValueCount++;
  10006. this._current = 0;
  10007. this._lastSecValueCount++;
  10008. };
  10009. /**
  10010. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10011. * @param newCount the count value to add to the monitored count
  10012. * @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.
  10013. */
  10014. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10015. if (!PerfCounter.Enabled) {
  10016. return;
  10017. }
  10018. this._current += newCount;
  10019. if (fetchResult) {
  10020. this._fetchResult();
  10021. }
  10022. };
  10023. /**
  10024. * Start monitoring this performance counter
  10025. */
  10026. PerfCounter.prototype.beginMonitoring = function () {
  10027. if (!PerfCounter.Enabled) {
  10028. return;
  10029. }
  10030. this._startMonitoringTime = Tools.Now;
  10031. };
  10032. /**
  10033. * Compute the time lapsed since the previous beginMonitoring() call.
  10034. * @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
  10035. */
  10036. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10037. if (newFrame === void 0) { newFrame = true; }
  10038. if (!PerfCounter.Enabled) {
  10039. return;
  10040. }
  10041. if (newFrame) {
  10042. this.fetchNewFrame();
  10043. }
  10044. var currentTime = Tools.Now;
  10045. this._current = currentTime - this._startMonitoringTime;
  10046. if (newFrame) {
  10047. this._fetchResult();
  10048. }
  10049. };
  10050. PerfCounter.prototype._fetchResult = function () {
  10051. this._totalAccumulated += this._current;
  10052. this._lastSecAccumulated += this._current;
  10053. // Min/Max update
  10054. this._min = Math.min(this._min, this._current);
  10055. this._max = Math.max(this._max, this._current);
  10056. this._average = this._totalAccumulated / this._totalValueCount;
  10057. // Reset last sec?
  10058. var now = Tools.Now;
  10059. if ((now - this._lastSecTime) > 1000) {
  10060. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10061. this._lastSecTime = now;
  10062. this._lastSecAccumulated = 0;
  10063. this._lastSecValueCount = 0;
  10064. }
  10065. };
  10066. PerfCounter.Enabled = true;
  10067. return PerfCounter;
  10068. }());
  10069. BABYLON.PerfCounter = PerfCounter;
  10070. /**
  10071. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10072. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10073. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10074. * @param name The name of the class, case should be preserved
  10075. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10076. */
  10077. function className(name, module) {
  10078. return function (target) {
  10079. target["__bjsclassName__"] = name;
  10080. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10081. };
  10082. }
  10083. BABYLON.className = className;
  10084. /**
  10085. * An implementation of a loop for asynchronous functions.
  10086. */
  10087. var AsyncLoop = /** @class */ (function () {
  10088. /**
  10089. * Constroctor.
  10090. * @param iterations the number of iterations.
  10091. * @param _fn the function to run each iteration
  10092. * @param _successCallback the callback that will be called upon succesful execution
  10093. * @param offset starting offset.
  10094. */
  10095. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10096. if (offset === void 0) { offset = 0; }
  10097. this.iterations = iterations;
  10098. this._fn = _fn;
  10099. this._successCallback = _successCallback;
  10100. this.index = offset - 1;
  10101. this._done = false;
  10102. }
  10103. /**
  10104. * Execute the next iteration. Must be called after the last iteration was finished.
  10105. */
  10106. AsyncLoop.prototype.executeNext = function () {
  10107. if (!this._done) {
  10108. if (this.index + 1 < this.iterations) {
  10109. ++this.index;
  10110. this._fn(this);
  10111. }
  10112. else {
  10113. this.breakLoop();
  10114. }
  10115. }
  10116. };
  10117. /**
  10118. * Break the loop and run the success callback.
  10119. */
  10120. AsyncLoop.prototype.breakLoop = function () {
  10121. this._done = true;
  10122. this._successCallback();
  10123. };
  10124. /**
  10125. * Helper function
  10126. */
  10127. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10128. if (offset === void 0) { offset = 0; }
  10129. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10130. loop.executeNext();
  10131. return loop;
  10132. };
  10133. /**
  10134. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10135. * @param iterations total number of iterations
  10136. * @param syncedIterations number of synchronous iterations in each async iteration.
  10137. * @param fn the function to call each iteration.
  10138. * @param callback a success call back that will be called when iterating stops.
  10139. * @param breakFunction a break condition (optional)
  10140. * @param timeout timeout settings for the setTimeout function. default - 0.
  10141. * @constructor
  10142. */
  10143. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10144. if (timeout === void 0) { timeout = 0; }
  10145. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10146. if (breakFunction && breakFunction())
  10147. loop.breakLoop();
  10148. else {
  10149. setTimeout(function () {
  10150. for (var i = 0; i < syncedIterations; ++i) {
  10151. var iteration = (loop.index * syncedIterations) + i;
  10152. if (iteration >= iterations)
  10153. break;
  10154. fn(iteration);
  10155. if (breakFunction && breakFunction()) {
  10156. loop.breakLoop();
  10157. break;
  10158. }
  10159. }
  10160. loop.executeNext();
  10161. }, timeout);
  10162. }
  10163. }, callback);
  10164. };
  10165. return AsyncLoop;
  10166. }());
  10167. BABYLON.AsyncLoop = AsyncLoop;
  10168. })(BABYLON || (BABYLON = {}));
  10169. //# sourceMappingURL=babylon.tools.js.map
  10170. var BABYLON;
  10171. (function (BABYLON) {
  10172. var PromiseStates;
  10173. (function (PromiseStates) {
  10174. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10175. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10176. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10177. })(PromiseStates || (PromiseStates = {}));
  10178. var FulFillmentAgregator = /** @class */ (function () {
  10179. function FulFillmentAgregator() {
  10180. this.count = 0;
  10181. this.target = 0;
  10182. this.results = [];
  10183. }
  10184. return FulFillmentAgregator;
  10185. }());
  10186. var InternalPromise = /** @class */ (function () {
  10187. function InternalPromise(resolver) {
  10188. var _this = this;
  10189. this._state = PromiseStates.Pending;
  10190. this._children = new Array();
  10191. this._rejectWasConsumed = false;
  10192. if (!resolver) {
  10193. return;
  10194. }
  10195. try {
  10196. resolver(function (value) {
  10197. _this._resolve(value);
  10198. }, function (reason) {
  10199. _this._reject(reason);
  10200. });
  10201. }
  10202. catch (e) {
  10203. this._reject(e);
  10204. }
  10205. }
  10206. Object.defineProperty(InternalPromise.prototype, "_result", {
  10207. get: function () {
  10208. return this._resultValue;
  10209. },
  10210. set: function (value) {
  10211. this._resultValue = value;
  10212. if (this._parent && this._parent._result === undefined) {
  10213. this._parent._result = value;
  10214. }
  10215. },
  10216. enumerable: true,
  10217. configurable: true
  10218. });
  10219. InternalPromise.prototype.catch = function (onRejected) {
  10220. return this.then(undefined, onRejected);
  10221. };
  10222. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10223. var _this = this;
  10224. var newPromise = new InternalPromise();
  10225. newPromise._onFulfilled = onFulfilled;
  10226. newPromise._onRejected = onRejected;
  10227. // Composition
  10228. this._children.push(newPromise);
  10229. newPromise._parent = this;
  10230. if (this._state !== PromiseStates.Pending) {
  10231. BABYLON.Tools.SetImmediate(function () {
  10232. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10233. var returnedValue = newPromise._resolve(_this._result);
  10234. if (returnedValue !== undefined && returnedValue !== null) {
  10235. if (returnedValue._state !== undefined) {
  10236. var returnedPromise = returnedValue;
  10237. newPromise._children.push(returnedPromise);
  10238. returnedPromise._parent = newPromise;
  10239. newPromise = returnedPromise;
  10240. }
  10241. else {
  10242. newPromise._result = returnedValue;
  10243. }
  10244. }
  10245. }
  10246. else {
  10247. newPromise._reject(_this._reason);
  10248. }
  10249. });
  10250. }
  10251. return newPromise;
  10252. };
  10253. InternalPromise.prototype._moveChildren = function (children) {
  10254. var _this = this;
  10255. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10256. this._children.forEach(function (child) {
  10257. child._parent = _this;
  10258. });
  10259. if (this._state === PromiseStates.Fulfilled) {
  10260. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10261. var child = _b[_i];
  10262. child._resolve(this._result);
  10263. }
  10264. }
  10265. else if (this._state === PromiseStates.Rejected) {
  10266. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10267. var child = _d[_c];
  10268. child._reject(this._reason);
  10269. }
  10270. }
  10271. var _a;
  10272. };
  10273. InternalPromise.prototype._resolve = function (value) {
  10274. try {
  10275. this._state = PromiseStates.Fulfilled;
  10276. var returnedValue = null;
  10277. if (this._onFulfilled) {
  10278. returnedValue = this._onFulfilled(value);
  10279. }
  10280. if (returnedValue !== undefined && returnedValue !== null) {
  10281. if (returnedValue._state !== undefined) {
  10282. // Transmit children
  10283. var returnedPromise = returnedValue;
  10284. returnedPromise._parent = this;
  10285. returnedPromise._moveChildren(this._children);
  10286. value = returnedPromise._result;
  10287. }
  10288. else {
  10289. value = returnedValue;
  10290. }
  10291. }
  10292. this._result = value;
  10293. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10294. var child = _a[_i];
  10295. child._resolve(value);
  10296. }
  10297. this._children.length = 0;
  10298. delete this._onFulfilled;
  10299. delete this._onRejected;
  10300. }
  10301. catch (e) {
  10302. this._reject(e, true);
  10303. }
  10304. };
  10305. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10306. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10307. this._state = PromiseStates.Rejected;
  10308. this._reason = reason;
  10309. if (this._onRejected && !onLocalThrow) {
  10310. try {
  10311. this._onRejected(reason);
  10312. this._rejectWasConsumed = true;
  10313. }
  10314. catch (e) {
  10315. reason = e;
  10316. }
  10317. }
  10318. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10319. var child = _a[_i];
  10320. if (this._rejectWasConsumed) {
  10321. child._resolve(null);
  10322. }
  10323. else {
  10324. child._reject(reason);
  10325. }
  10326. }
  10327. this._children.length = 0;
  10328. delete this._onFulfilled;
  10329. delete this._onRejected;
  10330. };
  10331. InternalPromise.resolve = function (value) {
  10332. var newPromise = new InternalPromise();
  10333. newPromise._resolve(value);
  10334. return newPromise;
  10335. };
  10336. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10337. promise.then(function (value) {
  10338. agregator.results[index] = value;
  10339. agregator.count++;
  10340. if (agregator.count === agregator.target) {
  10341. agregator.rootPromise._resolve(agregator.results);
  10342. }
  10343. return null;
  10344. }, function (reason) {
  10345. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10346. agregator.rootPromise._reject(reason);
  10347. }
  10348. });
  10349. };
  10350. InternalPromise.all = function (promises) {
  10351. var newPromise = new InternalPromise();
  10352. var agregator = new FulFillmentAgregator();
  10353. agregator.target = promises.length;
  10354. agregator.rootPromise = newPromise;
  10355. if (promises.length) {
  10356. for (var index = 0; index < promises.length; index++) {
  10357. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10358. }
  10359. }
  10360. else {
  10361. newPromise._resolve([]);
  10362. }
  10363. return newPromise;
  10364. };
  10365. InternalPromise.race = function (promises) {
  10366. var newPromise = new InternalPromise();
  10367. if (promises.length) {
  10368. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10369. var promise = promises_1[_i];
  10370. promise.then(function (value) {
  10371. if (newPromise) {
  10372. newPromise._resolve(value);
  10373. newPromise = null;
  10374. }
  10375. return null;
  10376. }, function (reason) {
  10377. if (newPromise) {
  10378. newPromise._reject(reason);
  10379. newPromise = null;
  10380. }
  10381. });
  10382. }
  10383. }
  10384. return newPromise;
  10385. };
  10386. return InternalPromise;
  10387. }());
  10388. /**
  10389. * Helper class that provides a small promise polyfill
  10390. */
  10391. var PromisePolyfill = /** @class */ (function () {
  10392. function PromisePolyfill() {
  10393. }
  10394. /**
  10395. * Static function used to check if the polyfill is required
  10396. * If this is the case then the function will inject the polyfill to window.Promise
  10397. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10398. */
  10399. PromisePolyfill.Apply = function (force) {
  10400. if (force === void 0) { force = false; }
  10401. if (force || typeof Promise === 'undefined') {
  10402. var root = window;
  10403. root.Promise = InternalPromise;
  10404. }
  10405. };
  10406. return PromisePolyfill;
  10407. }());
  10408. BABYLON.PromisePolyfill = PromisePolyfill;
  10409. })(BABYLON || (BABYLON = {}));
  10410. //# sourceMappingURL=babylon.promise.js.map
  10411. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10412. var BABYLON;
  10413. (function (BABYLON) {
  10414. /**
  10415. * Helper class to push actions to a pool of workers.
  10416. */
  10417. var WorkerPool = /** @class */ (function () {
  10418. /**
  10419. * Constructor
  10420. * @param workers Array of workers to use for actions
  10421. */
  10422. function WorkerPool(workers) {
  10423. this._pendingActions = new Array();
  10424. this._workerInfos = workers.map(function (worker) { return ({
  10425. worker: worker,
  10426. active: false
  10427. }); });
  10428. }
  10429. /**
  10430. * Terminates all workers and clears any pending actions.
  10431. */
  10432. WorkerPool.prototype.dispose = function () {
  10433. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10434. var workerInfo = _a[_i];
  10435. workerInfo.worker.terminate();
  10436. }
  10437. delete this._workerInfos;
  10438. delete this._pendingActions;
  10439. };
  10440. /**
  10441. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10442. * pended until a worker has completed its action.
  10443. * @param action The action to perform. Call onComplete when the action is complete.
  10444. */
  10445. WorkerPool.prototype.push = function (action) {
  10446. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10447. var workerInfo = _a[_i];
  10448. if (!workerInfo.active) {
  10449. this._execute(workerInfo, action);
  10450. return;
  10451. }
  10452. }
  10453. this._pendingActions.push(action);
  10454. };
  10455. WorkerPool.prototype._execute = function (workerInfo, action) {
  10456. var _this = this;
  10457. workerInfo.active = true;
  10458. action(workerInfo.worker, function () {
  10459. workerInfo.active = false;
  10460. var nextAction = _this._pendingActions.shift();
  10461. if (nextAction) {
  10462. _this._execute(workerInfo, nextAction);
  10463. }
  10464. });
  10465. };
  10466. return WorkerPool;
  10467. }());
  10468. BABYLON.WorkerPool = WorkerPool;
  10469. })(BABYLON || (BABYLON = {}));
  10470. //# sourceMappingURL=babylon.workerPool.js.map
  10471. var BABYLON;
  10472. (function (BABYLON) {
  10473. /**
  10474. * @hidden
  10475. **/
  10476. var _AlphaState = /** @class */ (function () {
  10477. /**
  10478. * Initializes the state.
  10479. */
  10480. function _AlphaState() {
  10481. this._isAlphaBlendDirty = false;
  10482. this._isBlendFunctionParametersDirty = false;
  10483. this._isBlendEquationParametersDirty = false;
  10484. this._isBlendConstantsDirty = false;
  10485. this._alphaBlend = false;
  10486. this._blendFunctionParameters = new Array(4);
  10487. this._blendEquationParameters = new Array(2);
  10488. this._blendConstants = new Array(4);
  10489. this.reset();
  10490. }
  10491. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10492. get: function () {
  10493. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10494. },
  10495. enumerable: true,
  10496. configurable: true
  10497. });
  10498. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10499. get: function () {
  10500. return this._alphaBlend;
  10501. },
  10502. set: function (value) {
  10503. if (this._alphaBlend === value) {
  10504. return;
  10505. }
  10506. this._alphaBlend = value;
  10507. this._isAlphaBlendDirty = true;
  10508. },
  10509. enumerable: true,
  10510. configurable: true
  10511. });
  10512. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10513. if (this._blendConstants[0] === r &&
  10514. this._blendConstants[1] === g &&
  10515. this._blendConstants[2] === b &&
  10516. this._blendConstants[3] === a) {
  10517. return;
  10518. }
  10519. this._blendConstants[0] = r;
  10520. this._blendConstants[1] = g;
  10521. this._blendConstants[2] = b;
  10522. this._blendConstants[3] = a;
  10523. this._isBlendConstantsDirty = true;
  10524. };
  10525. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10526. if (this._blendFunctionParameters[0] === value0 &&
  10527. this._blendFunctionParameters[1] === value1 &&
  10528. this._blendFunctionParameters[2] === value2 &&
  10529. this._blendFunctionParameters[3] === value3) {
  10530. return;
  10531. }
  10532. this._blendFunctionParameters[0] = value0;
  10533. this._blendFunctionParameters[1] = value1;
  10534. this._blendFunctionParameters[2] = value2;
  10535. this._blendFunctionParameters[3] = value3;
  10536. this._isBlendFunctionParametersDirty = true;
  10537. };
  10538. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10539. if (this._blendEquationParameters[0] === rgb &&
  10540. this._blendEquationParameters[1] === alpha) {
  10541. return;
  10542. }
  10543. this._blendEquationParameters[0] = rgb;
  10544. this._blendEquationParameters[1] = alpha;
  10545. this._isBlendEquationParametersDirty = true;
  10546. };
  10547. _AlphaState.prototype.reset = function () {
  10548. this._alphaBlend = false;
  10549. this._blendFunctionParameters[0] = null;
  10550. this._blendFunctionParameters[1] = null;
  10551. this._blendFunctionParameters[2] = null;
  10552. this._blendFunctionParameters[3] = null;
  10553. this._blendEquationParameters[0] = null;
  10554. this._blendEquationParameters[1] = null;
  10555. this._blendConstants[0] = null;
  10556. this._blendConstants[1] = null;
  10557. this._blendConstants[2] = null;
  10558. this._blendConstants[3] = null;
  10559. this._isAlphaBlendDirty = true;
  10560. this._isBlendFunctionParametersDirty = false;
  10561. this._isBlendEquationParametersDirty = false;
  10562. this._isBlendConstantsDirty = false;
  10563. };
  10564. _AlphaState.prototype.apply = function (gl) {
  10565. if (!this.isDirty) {
  10566. return;
  10567. }
  10568. // Alpha blend
  10569. if (this._isAlphaBlendDirty) {
  10570. if (this._alphaBlend) {
  10571. gl.enable(gl.BLEND);
  10572. }
  10573. else {
  10574. gl.disable(gl.BLEND);
  10575. }
  10576. this._isAlphaBlendDirty = false;
  10577. }
  10578. // Alpha function
  10579. if (this._isBlendFunctionParametersDirty) {
  10580. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10581. this._isBlendFunctionParametersDirty = false;
  10582. }
  10583. // Alpha equation
  10584. if (this._isBlendEquationParametersDirty) {
  10585. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10586. this._isBlendEquationParametersDirty = false;
  10587. }
  10588. // Constants
  10589. if (this._isBlendConstantsDirty) {
  10590. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10591. this._isBlendConstantsDirty = false;
  10592. }
  10593. };
  10594. return _AlphaState;
  10595. }());
  10596. BABYLON._AlphaState = _AlphaState;
  10597. })(BABYLON || (BABYLON = {}));
  10598. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10599. var BABYLON;
  10600. (function (BABYLON) {
  10601. /**
  10602. * @hidden
  10603. **/
  10604. var _DepthCullingState = /** @class */ (function () {
  10605. /**
  10606. * Initializes the state.
  10607. */
  10608. function _DepthCullingState() {
  10609. this._isDepthTestDirty = false;
  10610. this._isDepthMaskDirty = false;
  10611. this._isDepthFuncDirty = false;
  10612. this._isCullFaceDirty = false;
  10613. this._isCullDirty = false;
  10614. this._isZOffsetDirty = false;
  10615. this._isFrontFaceDirty = false;
  10616. this.reset();
  10617. }
  10618. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10619. get: function () {
  10620. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10621. },
  10622. enumerable: true,
  10623. configurable: true
  10624. });
  10625. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10626. get: function () {
  10627. return this._zOffset;
  10628. },
  10629. set: function (value) {
  10630. if (this._zOffset === value) {
  10631. return;
  10632. }
  10633. this._zOffset = value;
  10634. this._isZOffsetDirty = true;
  10635. },
  10636. enumerable: true,
  10637. configurable: true
  10638. });
  10639. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10640. get: function () {
  10641. return this._cullFace;
  10642. },
  10643. set: function (value) {
  10644. if (this._cullFace === value) {
  10645. return;
  10646. }
  10647. this._cullFace = value;
  10648. this._isCullFaceDirty = true;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10654. get: function () {
  10655. return this._cull;
  10656. },
  10657. set: function (value) {
  10658. if (this._cull === value) {
  10659. return;
  10660. }
  10661. this._cull = value;
  10662. this._isCullDirty = true;
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10668. get: function () {
  10669. return this._depthFunc;
  10670. },
  10671. set: function (value) {
  10672. if (this._depthFunc === value) {
  10673. return;
  10674. }
  10675. this._depthFunc = value;
  10676. this._isDepthFuncDirty = true;
  10677. },
  10678. enumerable: true,
  10679. configurable: true
  10680. });
  10681. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10682. get: function () {
  10683. return this._depthMask;
  10684. },
  10685. set: function (value) {
  10686. if (this._depthMask === value) {
  10687. return;
  10688. }
  10689. this._depthMask = value;
  10690. this._isDepthMaskDirty = true;
  10691. },
  10692. enumerable: true,
  10693. configurable: true
  10694. });
  10695. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10696. get: function () {
  10697. return this._depthTest;
  10698. },
  10699. set: function (value) {
  10700. if (this._depthTest === value) {
  10701. return;
  10702. }
  10703. this._depthTest = value;
  10704. this._isDepthTestDirty = true;
  10705. },
  10706. enumerable: true,
  10707. configurable: true
  10708. });
  10709. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10710. get: function () {
  10711. return this._frontFace;
  10712. },
  10713. set: function (value) {
  10714. if (this._frontFace === value) {
  10715. return;
  10716. }
  10717. this._frontFace = value;
  10718. this._isFrontFaceDirty = true;
  10719. },
  10720. enumerable: true,
  10721. configurable: true
  10722. });
  10723. _DepthCullingState.prototype.reset = function () {
  10724. this._depthMask = true;
  10725. this._depthTest = true;
  10726. this._depthFunc = null;
  10727. this._cullFace = null;
  10728. this._cull = null;
  10729. this._zOffset = 0;
  10730. this._frontFace = null;
  10731. this._isDepthTestDirty = true;
  10732. this._isDepthMaskDirty = true;
  10733. this._isDepthFuncDirty = false;
  10734. this._isCullFaceDirty = false;
  10735. this._isCullDirty = false;
  10736. this._isZOffsetDirty = false;
  10737. this._isFrontFaceDirty = false;
  10738. };
  10739. _DepthCullingState.prototype.apply = function (gl) {
  10740. if (!this.isDirty) {
  10741. return;
  10742. }
  10743. // Cull
  10744. if (this._isCullDirty) {
  10745. if (this.cull) {
  10746. gl.enable(gl.CULL_FACE);
  10747. }
  10748. else {
  10749. gl.disable(gl.CULL_FACE);
  10750. }
  10751. this._isCullDirty = false;
  10752. }
  10753. // Cull face
  10754. if (this._isCullFaceDirty) {
  10755. gl.cullFace(this.cullFace);
  10756. this._isCullFaceDirty = false;
  10757. }
  10758. // Depth mask
  10759. if (this._isDepthMaskDirty) {
  10760. gl.depthMask(this.depthMask);
  10761. this._isDepthMaskDirty = false;
  10762. }
  10763. // Depth test
  10764. if (this._isDepthTestDirty) {
  10765. if (this.depthTest) {
  10766. gl.enable(gl.DEPTH_TEST);
  10767. }
  10768. else {
  10769. gl.disable(gl.DEPTH_TEST);
  10770. }
  10771. this._isDepthTestDirty = false;
  10772. }
  10773. // Depth func
  10774. if (this._isDepthFuncDirty) {
  10775. gl.depthFunc(this.depthFunc);
  10776. this._isDepthFuncDirty = false;
  10777. }
  10778. // zOffset
  10779. if (this._isZOffsetDirty) {
  10780. if (this.zOffset) {
  10781. gl.enable(gl.POLYGON_OFFSET_FILL);
  10782. gl.polygonOffset(this.zOffset, 0);
  10783. }
  10784. else {
  10785. gl.disable(gl.POLYGON_OFFSET_FILL);
  10786. }
  10787. this._isZOffsetDirty = false;
  10788. }
  10789. // Front face
  10790. if (this._isFrontFaceDirty) {
  10791. gl.frontFace(this.frontFace);
  10792. this._isFrontFaceDirty = false;
  10793. }
  10794. };
  10795. return _DepthCullingState;
  10796. }());
  10797. BABYLON._DepthCullingState = _DepthCullingState;
  10798. })(BABYLON || (BABYLON = {}));
  10799. //# sourceMappingURL=babylon.depthCullingState.js.map
  10800. var BABYLON;
  10801. (function (BABYLON) {
  10802. /**
  10803. * @hidden
  10804. **/
  10805. var _StencilState = /** @class */ (function () {
  10806. function _StencilState() {
  10807. this._isStencilTestDirty = false;
  10808. this._isStencilMaskDirty = false;
  10809. this._isStencilFuncDirty = false;
  10810. this._isStencilOpDirty = false;
  10811. this.reset();
  10812. }
  10813. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10814. get: function () {
  10815. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10821. get: function () {
  10822. return this._stencilFunc;
  10823. },
  10824. set: function (value) {
  10825. if (this._stencilFunc === value) {
  10826. return;
  10827. }
  10828. this._stencilFunc = value;
  10829. this._isStencilFuncDirty = true;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10835. get: function () {
  10836. return this._stencilFuncRef;
  10837. },
  10838. set: function (value) {
  10839. if (this._stencilFuncRef === value) {
  10840. return;
  10841. }
  10842. this._stencilFuncRef = value;
  10843. this._isStencilFuncDirty = true;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10849. get: function () {
  10850. return this._stencilFuncMask;
  10851. },
  10852. set: function (value) {
  10853. if (this._stencilFuncMask === value) {
  10854. return;
  10855. }
  10856. this._stencilFuncMask = value;
  10857. this._isStencilFuncDirty = true;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10863. get: function () {
  10864. return this._stencilOpStencilFail;
  10865. },
  10866. set: function (value) {
  10867. if (this._stencilOpStencilFail === value) {
  10868. return;
  10869. }
  10870. this._stencilOpStencilFail = value;
  10871. this._isStencilOpDirty = true;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10877. get: function () {
  10878. return this._stencilOpDepthFail;
  10879. },
  10880. set: function (value) {
  10881. if (this._stencilOpDepthFail === value) {
  10882. return;
  10883. }
  10884. this._stencilOpDepthFail = value;
  10885. this._isStencilOpDirty = true;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10891. get: function () {
  10892. return this._stencilOpStencilDepthPass;
  10893. },
  10894. set: function (value) {
  10895. if (this._stencilOpStencilDepthPass === value) {
  10896. return;
  10897. }
  10898. this._stencilOpStencilDepthPass = value;
  10899. this._isStencilOpDirty = true;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10905. get: function () {
  10906. return this._stencilMask;
  10907. },
  10908. set: function (value) {
  10909. if (this._stencilMask === value) {
  10910. return;
  10911. }
  10912. this._stencilMask = value;
  10913. this._isStencilMaskDirty = true;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10919. get: function () {
  10920. return this._stencilTest;
  10921. },
  10922. set: function (value) {
  10923. if (this._stencilTest === value) {
  10924. return;
  10925. }
  10926. this._stencilTest = value;
  10927. this._isStencilTestDirty = true;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. _StencilState.prototype.reset = function () {
  10933. this._stencilTest = false;
  10934. this._stencilMask = 0xFF;
  10935. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10936. this._stencilFuncRef = 1;
  10937. this._stencilFuncMask = 0xFF;
  10938. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10939. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10940. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10941. this._isStencilTestDirty = true;
  10942. this._isStencilMaskDirty = true;
  10943. this._isStencilFuncDirty = true;
  10944. this._isStencilOpDirty = true;
  10945. };
  10946. _StencilState.prototype.apply = function (gl) {
  10947. if (!this.isDirty) {
  10948. return;
  10949. }
  10950. // Stencil test
  10951. if (this._isStencilTestDirty) {
  10952. if (this.stencilTest) {
  10953. gl.enable(gl.STENCIL_TEST);
  10954. }
  10955. else {
  10956. gl.disable(gl.STENCIL_TEST);
  10957. }
  10958. this._isStencilTestDirty = false;
  10959. }
  10960. // Stencil mask
  10961. if (this._isStencilMaskDirty) {
  10962. gl.stencilMask(this.stencilMask);
  10963. this._isStencilMaskDirty = false;
  10964. }
  10965. // Stencil func
  10966. if (this._isStencilFuncDirty) {
  10967. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10968. this._isStencilFuncDirty = false;
  10969. }
  10970. // Stencil op
  10971. if (this._isStencilOpDirty) {
  10972. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10973. this._isStencilOpDirty = false;
  10974. }
  10975. };
  10976. return _StencilState;
  10977. }());
  10978. BABYLON._StencilState = _StencilState;
  10979. })(BABYLON || (BABYLON = {}));
  10980. //# sourceMappingURL=babylon.stencilState.js.map
  10981. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10982. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10983. s = arguments[i];
  10984. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10985. t[p] = s[p];
  10986. }
  10987. return t;
  10988. };
  10989. var BABYLON;
  10990. (function (BABYLON) {
  10991. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10992. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10993. };
  10994. var compileRawShader = function (gl, source, type) {
  10995. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10996. gl.shaderSource(shader, source);
  10997. gl.compileShader(shader);
  10998. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10999. var log = gl.getShaderInfoLog(shader);
  11000. if (log) {
  11001. throw new Error(log);
  11002. }
  11003. }
  11004. if (!shader) {
  11005. throw new Error("Something went wrong while compile the shader.");
  11006. }
  11007. return shader;
  11008. };
  11009. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11010. var magFilter = gl.NEAREST;
  11011. var minFilter = gl.NEAREST;
  11012. switch (samplingMode) {
  11013. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11014. magFilter = gl.LINEAR;
  11015. if (generateMipMaps) {
  11016. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11017. }
  11018. else {
  11019. minFilter = gl.LINEAR;
  11020. }
  11021. break;
  11022. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11023. magFilter = gl.LINEAR;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11026. }
  11027. else {
  11028. minFilter = gl.LINEAR;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11032. magFilter = gl.NEAREST;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11035. }
  11036. else {
  11037. minFilter = gl.NEAREST;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11041. magFilter = gl.NEAREST;
  11042. if (generateMipMaps) {
  11043. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11044. }
  11045. else {
  11046. minFilter = gl.NEAREST;
  11047. }
  11048. break;
  11049. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11050. magFilter = gl.NEAREST;
  11051. if (generateMipMaps) {
  11052. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11053. }
  11054. else {
  11055. minFilter = gl.LINEAR;
  11056. }
  11057. break;
  11058. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11059. magFilter = gl.NEAREST;
  11060. if (generateMipMaps) {
  11061. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11062. }
  11063. else {
  11064. minFilter = gl.LINEAR;
  11065. }
  11066. break;
  11067. case BABYLON.Texture.NEAREST_LINEAR:
  11068. magFilter = gl.NEAREST;
  11069. minFilter = gl.LINEAR;
  11070. break;
  11071. case BABYLON.Texture.NEAREST_NEAREST:
  11072. magFilter = gl.NEAREST;
  11073. minFilter = gl.NEAREST;
  11074. break;
  11075. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11076. magFilter = gl.LINEAR;
  11077. if (generateMipMaps) {
  11078. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11079. }
  11080. else {
  11081. minFilter = gl.NEAREST;
  11082. }
  11083. break;
  11084. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11085. magFilter = gl.LINEAR;
  11086. if (generateMipMaps) {
  11087. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11088. }
  11089. else {
  11090. minFilter = gl.NEAREST;
  11091. }
  11092. break;
  11093. case BABYLON.Texture.LINEAR_LINEAR:
  11094. magFilter = gl.LINEAR;
  11095. minFilter = gl.LINEAR;
  11096. break;
  11097. case BABYLON.Texture.LINEAR_NEAREST:
  11098. magFilter = gl.LINEAR;
  11099. minFilter = gl.NEAREST;
  11100. break;
  11101. }
  11102. return {
  11103. min: minFilter,
  11104. mag: magFilter
  11105. };
  11106. };
  11107. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11108. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11109. var img;
  11110. var onload = function () {
  11111. loadedImages[index] = img;
  11112. loadedImages._internalCount++;
  11113. if (scene) {
  11114. scene._removePendingData(img);
  11115. }
  11116. if (loadedImages._internalCount === 6) {
  11117. onfinish(loadedImages);
  11118. }
  11119. };
  11120. var onerror = function (message, exception) {
  11121. if (scene) {
  11122. scene._removePendingData(img);
  11123. }
  11124. if (onErrorCallBack) {
  11125. onErrorCallBack(message, exception);
  11126. }
  11127. };
  11128. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11129. if (scene) {
  11130. scene._addPendingData(img);
  11131. }
  11132. };
  11133. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11134. if (onError === void 0) { onError = null; }
  11135. var loadedImages = [];
  11136. loadedImages._internalCount = 0;
  11137. for (var index = 0; index < 6; index++) {
  11138. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11139. }
  11140. };
  11141. var BufferPointer = /** @class */ (function () {
  11142. function BufferPointer() {
  11143. }
  11144. return BufferPointer;
  11145. }());
  11146. /**
  11147. * Interface for attribute information associated with buffer instanciation
  11148. */
  11149. var InstancingAttributeInfo = /** @class */ (function () {
  11150. function InstancingAttributeInfo() {
  11151. }
  11152. return InstancingAttributeInfo;
  11153. }());
  11154. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11155. /**
  11156. * Define options used to create a render target texture
  11157. */
  11158. var RenderTargetCreationOptions = /** @class */ (function () {
  11159. function RenderTargetCreationOptions() {
  11160. }
  11161. return RenderTargetCreationOptions;
  11162. }());
  11163. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11164. /**
  11165. * Define options used to create a depth texture
  11166. */
  11167. var DepthTextureCreationOptions = /** @class */ (function () {
  11168. function DepthTextureCreationOptions() {
  11169. }
  11170. return DepthTextureCreationOptions;
  11171. }());
  11172. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11173. /**
  11174. * Class used to describe the capabilities of the engine relatively to the current browser
  11175. */
  11176. var EngineCapabilities = /** @class */ (function () {
  11177. function EngineCapabilities() {
  11178. }
  11179. return EngineCapabilities;
  11180. }());
  11181. BABYLON.EngineCapabilities = EngineCapabilities;
  11182. /**
  11183. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11184. */
  11185. var Engine = /** @class */ (function () {
  11186. /**
  11187. * Creates a new engine
  11188. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11189. * @param antialias defines enable antialiasing (default: false)
  11190. * @param options defines further options to be sent to the getContext() function
  11191. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11192. */
  11193. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11194. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11195. var _this = this;
  11196. // Public members
  11197. /**
  11198. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11199. */
  11200. this.forcePOTTextures = false;
  11201. /**
  11202. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11203. */
  11204. this.isFullscreen = false;
  11205. /**
  11206. * Gets a boolean indicating if the pointer is currently locked
  11207. */
  11208. this.isPointerLock = false;
  11209. /**
  11210. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11211. */
  11212. this.cullBackFaces = true;
  11213. /**
  11214. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11215. */
  11216. this.renderEvenInBackground = true;
  11217. /**
  11218. * Gets or sets a boolean indicating that cache can be kept between frames
  11219. */
  11220. this.preventCacheWipeBetweenFrames = false;
  11221. /**
  11222. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11223. **/
  11224. this.enableOfflineSupport = false;
  11225. /**
  11226. * 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)
  11227. **/
  11228. this.disableManifestCheck = false;
  11229. /**
  11230. * Gets the list of created scenes
  11231. */
  11232. this.scenes = new Array();
  11233. /**
  11234. * Gets the list of created postprocesses
  11235. */
  11236. this.postProcesses = new Array();
  11237. // Observables
  11238. /**
  11239. * Observable event triggered each time the rendering canvas is resized
  11240. */
  11241. this.onResizeObservable = new BABYLON.Observable();
  11242. /**
  11243. * Observable event triggered each time the canvas loses focus
  11244. */
  11245. this.onCanvasBlurObservable = new BABYLON.Observable();
  11246. /**
  11247. * Observable event triggered each time the canvas gains focus
  11248. */
  11249. this.onCanvasFocusObservable = new BABYLON.Observable();
  11250. /**
  11251. * Observable event triggered each time the canvas receives pointerout event
  11252. */
  11253. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11254. /**
  11255. * Observable event triggered before each texture is initialized
  11256. */
  11257. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11258. //WebVR
  11259. this._vrDisplay = undefined;
  11260. this._vrSupported = false;
  11261. this._vrExclusivePointerMode = false;
  11262. // Uniform buffers list
  11263. /**
  11264. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11265. */
  11266. this.disableUniformBuffers = false;
  11267. /** @hidden */
  11268. this._uniformBuffers = new Array();
  11269. // Observables
  11270. /**
  11271. * Observable raised when the engine begins a new frame
  11272. */
  11273. this.onBeginFrameObservable = new BABYLON.Observable();
  11274. /**
  11275. * Observable raised when the engine ends the current frame
  11276. */
  11277. this.onEndFrameObservable = new BABYLON.Observable();
  11278. /**
  11279. * Observable raised when the engine is about to compile a shader
  11280. */
  11281. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11282. /**
  11283. * Observable raised when the engine has jsut compiled a shader
  11284. */
  11285. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11286. this._windowIsBackground = false;
  11287. this._webGLVersion = 1.0;
  11288. /** @hidden */
  11289. this._badOS = false;
  11290. /** @hidden */
  11291. this._badDesktopOS = false;
  11292. /**
  11293. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11294. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11295. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11296. */
  11297. this.disableTextureBindingOptimization = false;
  11298. /**
  11299. * Observable signaled when VR display mode changes
  11300. */
  11301. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11302. /**
  11303. * Observable signaled when VR request present is complete
  11304. */
  11305. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11306. /**
  11307. * Observable signaled when VR request present starts
  11308. */
  11309. this.onVRRequestPresentStart = new BABYLON.Observable();
  11310. this._colorWrite = true;
  11311. /** @hidden */
  11312. this._drawCalls = new BABYLON.PerfCounter();
  11313. /** @hidden */
  11314. this._textureCollisions = new BABYLON.PerfCounter();
  11315. this._renderingQueueLaunched = false;
  11316. this._activeRenderLoops = new Array();
  11317. // Deterministic lockstepMaxSteps
  11318. this._deterministicLockstep = false;
  11319. this._lockstepMaxSteps = 4;
  11320. // Lost context
  11321. /**
  11322. * Observable signaled when a context lost event is raised
  11323. */
  11324. this.onContextLostObservable = new BABYLON.Observable();
  11325. /**
  11326. * Observable signaled when a context restored event is raised
  11327. */
  11328. this.onContextRestoredObservable = new BABYLON.Observable();
  11329. this._contextWasLost = false;
  11330. this._doNotHandleContextLost = false;
  11331. // FPS
  11332. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11333. this._fps = 60;
  11334. this._deltaTime = 0;
  11335. /**
  11336. * Turn this value on if you want to pause FPS computation when in background
  11337. */
  11338. this.disablePerformanceMonitorInBackground = false;
  11339. // States
  11340. /** @hidden */
  11341. this._depthCullingState = new BABYLON._DepthCullingState();
  11342. /** @hidden */
  11343. this._stencilState = new BABYLON._StencilState();
  11344. /** @hidden */
  11345. this._alphaState = new BABYLON._AlphaState();
  11346. /** @hidden */
  11347. this._alphaMode = Engine.ALPHA_DISABLE;
  11348. // Cache
  11349. this._internalTexturesCache = new Array();
  11350. /** @hidden */
  11351. this._activeChannel = 0;
  11352. this._currentTextureChannel = -1;
  11353. /** @hidden */
  11354. this._boundTexturesCache = {};
  11355. this._compiledEffects = {};
  11356. this._vertexAttribArraysEnabled = [];
  11357. this._uintIndicesCurrentlySet = false;
  11358. this._currentBoundBuffer = new Array();
  11359. this._currentBufferPointers = new Array();
  11360. this._currentInstanceLocations = new Array();
  11361. this._currentInstanceBuffers = new Array();
  11362. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11363. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11364. this._vaoRecordInProgress = false;
  11365. this._mustWipeVertexAttributes = false;
  11366. this._nextFreeTextureSlots = new Array();
  11367. this._maxSimultaneousTextures = 0;
  11368. this._activeRequests = new Array();
  11369. // Hardware supported Compressed Textures
  11370. this._texturesSupported = new Array();
  11371. this._onVRFullScreenTriggered = function () {
  11372. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11373. //get the old size before we change
  11374. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11375. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11376. //get the width and height, change the render size
  11377. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11378. _this.setHardwareScalingLevel(1);
  11379. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11380. }
  11381. else {
  11382. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11383. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11384. }
  11385. };
  11386. this._boundUniforms = {};
  11387. // Register promises
  11388. BABYLON.PromisePolyfill.Apply();
  11389. var canvas = null;
  11390. Engine.Instances.push(this);
  11391. if (!canvasOrContext) {
  11392. return;
  11393. }
  11394. options = options || {};
  11395. if (canvasOrContext.getContext) {
  11396. canvas = canvasOrContext;
  11397. this._renderingCanvas = canvas;
  11398. if (antialias != null) {
  11399. options.antialias = antialias;
  11400. }
  11401. if (options.deterministicLockstep === undefined) {
  11402. options.deterministicLockstep = false;
  11403. }
  11404. if (options.lockstepMaxSteps === undefined) {
  11405. options.lockstepMaxSteps = 4;
  11406. }
  11407. if (options.preserveDrawingBuffer === undefined) {
  11408. options.preserveDrawingBuffer = false;
  11409. }
  11410. if (options.audioEngine === undefined) {
  11411. options.audioEngine = true;
  11412. }
  11413. if (options.stencil === undefined) {
  11414. options.stencil = true;
  11415. }
  11416. this._deterministicLockstep = options.deterministicLockstep;
  11417. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11418. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11419. // Exceptions
  11420. if (navigator && navigator.userAgent) {
  11421. var ua = navigator.userAgent;
  11422. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11423. var exception = _a[_i];
  11424. var key = exception.key;
  11425. var targets = exception.targets;
  11426. if (ua.indexOf(key) > -1) {
  11427. if (exception.capture && exception.captureConstraint) {
  11428. var capture = exception.capture;
  11429. var constraint = exception.captureConstraint;
  11430. var regex = new RegExp(capture);
  11431. var matches = regex.exec(ua);
  11432. if (matches && matches.length > 0) {
  11433. var capturedValue = parseInt(matches[matches.length - 1]);
  11434. if (capturedValue >= constraint) {
  11435. continue;
  11436. }
  11437. }
  11438. }
  11439. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11440. var target = targets_1[_b];
  11441. switch (target) {
  11442. case "uniformBuffer":
  11443. this.disableUniformBuffers = true;
  11444. break;
  11445. case "textureBindingOptimization":
  11446. this.disableTextureBindingOptimization = true;
  11447. break;
  11448. }
  11449. }
  11450. }
  11451. }
  11452. }
  11453. // GL
  11454. if (!options.disableWebGL2Support) {
  11455. try {
  11456. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11457. if (this._gl) {
  11458. this._webGLVersion = 2.0;
  11459. }
  11460. }
  11461. catch (e) {
  11462. // Do nothing
  11463. }
  11464. }
  11465. if (!this._gl) {
  11466. if (!canvas) {
  11467. throw new Error("The provided canvas is null or undefined.");
  11468. }
  11469. try {
  11470. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11471. }
  11472. catch (e) {
  11473. throw new Error("WebGL not supported");
  11474. }
  11475. }
  11476. if (!this._gl) {
  11477. throw new Error("WebGL not supported");
  11478. }
  11479. this._onCanvasFocus = function () {
  11480. _this.onCanvasFocusObservable.notifyObservers(_this);
  11481. };
  11482. this._onCanvasBlur = function () {
  11483. _this.onCanvasBlurObservable.notifyObservers(_this);
  11484. };
  11485. canvas.addEventListener("focus", this._onCanvasFocus);
  11486. canvas.addEventListener("blur", this._onCanvasBlur);
  11487. this._onBlur = function () {
  11488. if (_this.disablePerformanceMonitorInBackground) {
  11489. _this._performanceMonitor.disable();
  11490. }
  11491. _this._windowIsBackground = true;
  11492. };
  11493. this._onFocus = function () {
  11494. if (_this.disablePerformanceMonitorInBackground) {
  11495. _this._performanceMonitor.enable();
  11496. }
  11497. _this._windowIsBackground = false;
  11498. };
  11499. this._onCanvasPointerOut = function (ev) {
  11500. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11501. };
  11502. window.addEventListener("blur", this._onBlur);
  11503. window.addEventListener("focus", this._onFocus);
  11504. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11505. // Context lost
  11506. if (!this._doNotHandleContextLost) {
  11507. this._onContextLost = function (evt) {
  11508. evt.preventDefault();
  11509. _this._contextWasLost = true;
  11510. BABYLON.Tools.Warn("WebGL context lost.");
  11511. _this.onContextLostObservable.notifyObservers(_this);
  11512. };
  11513. this._onContextRestored = function (evt) {
  11514. // Adding a timeout to avoid race condition at browser level
  11515. setTimeout(function () {
  11516. // Rebuild gl context
  11517. _this._initGLContext();
  11518. // Rebuild effects
  11519. _this._rebuildEffects();
  11520. // Rebuild textures
  11521. _this._rebuildInternalTextures();
  11522. // Rebuild buffers
  11523. _this._rebuildBuffers();
  11524. // Cache
  11525. _this.wipeCaches(true);
  11526. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11527. _this.onContextRestoredObservable.notifyObservers(_this);
  11528. _this._contextWasLost = false;
  11529. }, 0);
  11530. };
  11531. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11532. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11533. }
  11534. }
  11535. else {
  11536. this._gl = canvasOrContext;
  11537. this._renderingCanvas = this._gl.canvas;
  11538. if (this._gl.renderbufferStorageMultisample) {
  11539. this._webGLVersion = 2.0;
  11540. }
  11541. options.stencil = this._gl.getContextAttributes().stencil;
  11542. }
  11543. // Viewport
  11544. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11545. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11546. this.resize();
  11547. this._isStencilEnable = options.stencil ? true : false;
  11548. this._initGLContext();
  11549. if (canvas) {
  11550. // Fullscreen
  11551. this._onFullscreenChange = function () {
  11552. if (document.fullscreen !== undefined) {
  11553. _this.isFullscreen = document.fullscreen;
  11554. }
  11555. else if (document.mozFullScreen !== undefined) {
  11556. _this.isFullscreen = document.mozFullScreen;
  11557. }
  11558. else if (document.webkitIsFullScreen !== undefined) {
  11559. _this.isFullscreen = document.webkitIsFullScreen;
  11560. }
  11561. else if (document.msIsFullScreen !== undefined) {
  11562. _this.isFullscreen = document.msIsFullScreen;
  11563. }
  11564. // Pointer lock
  11565. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11566. canvas.requestPointerLock = canvas.requestPointerLock ||
  11567. canvas.msRequestPointerLock ||
  11568. canvas.mozRequestPointerLock ||
  11569. canvas.webkitRequestPointerLock;
  11570. if (canvas.requestPointerLock) {
  11571. canvas.requestPointerLock();
  11572. }
  11573. }
  11574. };
  11575. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11576. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11577. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11578. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11579. // Pointer lock
  11580. this._onPointerLockChange = function () {
  11581. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11582. document.webkitPointerLockElement === canvas ||
  11583. document.msPointerLockElement === canvas ||
  11584. document.pointerLockElement === canvas);
  11585. };
  11586. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11587. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11588. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11589. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11590. this._onVRDisplayPointerRestricted = function () {
  11591. if (canvas) {
  11592. canvas.requestPointerLock();
  11593. }
  11594. };
  11595. this._onVRDisplayPointerUnrestricted = function () {
  11596. document.exitPointerLock();
  11597. };
  11598. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11599. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11600. }
  11601. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11602. Engine.audioEngine = new BABYLON.AudioEngine();
  11603. }
  11604. // Prepare buffer pointers
  11605. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11606. this._currentBufferPointers[i] = new BufferPointer();
  11607. }
  11608. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11609. // Load WebVR Devices
  11610. if (options.autoEnableWebVR) {
  11611. this.initWebVR();
  11612. }
  11613. // Detect if we are running on a faulty buggy OS.
  11614. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11615. // Detect if we are running on a faulty buggy desktop OS.
  11616. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11617. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11618. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11619. }
  11620. Object.defineProperty(Engine, "LastCreatedEngine", {
  11621. /**
  11622. * Gets the latest created engine
  11623. */
  11624. get: function () {
  11625. if (Engine.Instances.length === 0) {
  11626. return null;
  11627. }
  11628. return Engine.Instances[Engine.Instances.length - 1];
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. Object.defineProperty(Engine, "LastCreatedScene", {
  11634. /**
  11635. * Gets the latest created scene
  11636. */
  11637. get: function () {
  11638. var lastCreatedEngine = Engine.LastCreatedEngine;
  11639. if (!lastCreatedEngine) {
  11640. return null;
  11641. }
  11642. if (lastCreatedEngine.scenes.length === 0) {
  11643. return null;
  11644. }
  11645. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. /**
  11651. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11652. * @param flag defines which part of the materials must be marked as dirty
  11653. * @param predicate defines a predicate used to filter which materials should be affected
  11654. */
  11655. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11656. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11657. var engine = Engine.Instances[engineIndex];
  11658. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11659. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11660. }
  11661. }
  11662. };
  11663. Object.defineProperty(Engine, "NEVER", {
  11664. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11665. get: function () {
  11666. return Engine._NEVER;
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Object.defineProperty(Engine, "ALWAYS", {
  11672. /** 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 */
  11673. get: function () {
  11674. return Engine._ALWAYS;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine, "LESS", {
  11680. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11681. get: function () {
  11682. return Engine._LESS;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Engine, "EQUAL", {
  11688. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11689. get: function () {
  11690. return Engine._EQUAL;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine, "LEQUAL", {
  11696. /** 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 */
  11697. get: function () {
  11698. return Engine._LEQUAL;
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(Engine, "GREATER", {
  11704. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11705. get: function () {
  11706. return Engine._GREATER;
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Engine, "GEQUAL", {
  11712. /** 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 */
  11713. get: function () {
  11714. return Engine._GEQUAL;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Engine, "NOTEQUAL", {
  11720. /** 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 */
  11721. get: function () {
  11722. return Engine._NOTEQUAL;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine, "KEEP", {
  11728. /** Passed to stencilOperation to specify that stencil value must be kept */
  11729. get: function () {
  11730. return Engine._KEEP;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine, "REPLACE", {
  11736. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11737. get: function () {
  11738. return Engine._REPLACE;
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(Engine, "INCR", {
  11744. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11745. get: function () {
  11746. return Engine._INCR;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Engine, "DECR", {
  11752. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11753. get: function () {
  11754. return Engine._DECR;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(Engine, "INVERT", {
  11760. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11761. get: function () {
  11762. return Engine._INVERT;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(Engine, "INCR_WRAP", {
  11768. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11769. get: function () {
  11770. return Engine._INCR_WRAP;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. Object.defineProperty(Engine, "DECR_WRAP", {
  11776. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11777. get: function () {
  11778. return Engine._DECR_WRAP;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11784. // Alpha
  11785. /** Defines that alpha blending is disabled */
  11786. get: function () {
  11787. return Engine._ALPHA_DISABLE;
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11793. /** Defines that alpha blending to SRC + DEST */
  11794. get: function () {
  11795. return Engine._ALPHA_ONEONE;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(Engine, "ALPHA_ADD", {
  11801. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11802. get: function () {
  11803. return Engine._ALPHA_ADD;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11809. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11810. get: function () {
  11811. return Engine._ALPHA_COMBINE;
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11817. /** Defines that alpha blending to DEST - SRC * DEST */
  11818. get: function () {
  11819. return Engine._ALPHA_SUBTRACT;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11825. /** Defines that alpha blending to SRC * DEST */
  11826. get: function () {
  11827. return Engine._ALPHA_MULTIPLY;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11833. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11834. get: function () {
  11835. return Engine._ALPHA_MAXIMIZED;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11841. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11842. get: function () {
  11843. return Engine._ALPHA_PREMULTIPLIED;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11849. /**
  11850. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11851. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11852. */
  11853. get: function () {
  11854. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11855. },
  11856. enumerable: true,
  11857. configurable: true
  11858. });
  11859. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11860. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11861. get: function () {
  11862. return Engine._ALPHA_INTERPOLATE;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11868. /**
  11869. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11870. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11871. */
  11872. get: function () {
  11873. return Engine._ALPHA_SCREENMODE;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11879. // Delays
  11880. /** Defines that the ressource is not delayed*/
  11881. get: function () {
  11882. return Engine._DELAYLOADSTATE_NONE;
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11888. /** Defines that the ressource was successfully delay loaded */
  11889. get: function () {
  11890. return Engine._DELAYLOADSTATE_LOADED;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11896. /** Defines that the ressource is currently delay loading */
  11897. get: function () {
  11898. return Engine._DELAYLOADSTATE_LOADING;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11904. /** Defines that the ressource is delayed and has not started loading */
  11905. get: function () {
  11906. return Engine._DELAYLOADSTATE_NOTLOADED;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11912. /** ALPHA */
  11913. get: function () {
  11914. return Engine._TEXTUREFORMAT_ALPHA;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11920. /** LUMINANCE */
  11921. get: function () {
  11922. return Engine._TEXTUREFORMAT_LUMINANCE;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11928. /**
  11929. * R32F
  11930. */
  11931. get: function () {
  11932. return Engine._TEXTUREFORMAT_R32F;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11938. /**
  11939. * RG32F
  11940. */
  11941. get: function () {
  11942. return Engine._TEXTUREFORMAT_RG32F;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11948. /**
  11949. * RGB32F
  11950. */
  11951. get: function () {
  11952. return Engine._TEXTUREFORMAT_RGB32F;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11958. /**
  11959. * RGBA32F
  11960. */
  11961. get: function () {
  11962. return Engine._TEXTUREFORMAT_RGBA32F;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11968. /** LUMINANCE_ALPHA */
  11969. get: function () {
  11970. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11976. /** RGB */
  11977. get: function () {
  11978. return Engine._TEXTUREFORMAT_RGB;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11984. /** RGBA */
  11985. get: function () {
  11986. return Engine._TEXTUREFORMAT_RGBA;
  11987. },
  11988. enumerable: true,
  11989. configurable: true
  11990. });
  11991. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11992. /** UNSIGNED_INT */
  11993. get: function () {
  11994. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12000. /** FLOAT */
  12001. get: function () {
  12002. return Engine._TEXTURETYPE_FLOAT;
  12003. },
  12004. enumerable: true,
  12005. configurable: true
  12006. });
  12007. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12008. /** HALF_FLOAT */
  12009. get: function () {
  12010. return Engine._TEXTURETYPE_HALF_FLOAT;
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12016. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12017. get: function () {
  12018. return Engine._SCALEMODE_FLOOR;
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12024. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12025. get: function () {
  12026. return Engine._SCALEMODE_NEAREST;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12032. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12033. get: function () {
  12034. return Engine._SCALEMODE_CEILING;
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(Engine, "Version", {
  12040. /**
  12041. * Returns the current version of the framework
  12042. */
  12043. get: function () {
  12044. return "3.3.0-alpha.2";
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12050. /**
  12051. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12052. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12053. */
  12054. get: function () {
  12055. return this._vrExclusivePointerMode;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12061. /**
  12062. * Gets a boolean indicating that the engine supports uniform buffers
  12063. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12064. */
  12065. get: function () {
  12066. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12067. },
  12068. enumerable: true,
  12069. configurable: true
  12070. });
  12071. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12072. /**
  12073. * Gets a boolean indicating that only power of 2 textures are supported
  12074. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12075. */
  12076. get: function () {
  12077. return this._webGLVersion < 2 || this.forcePOTTextures;
  12078. },
  12079. enumerable: true,
  12080. configurable: true
  12081. });
  12082. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12083. /**
  12084. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12085. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12086. */
  12087. get: function () {
  12088. return this._doNotHandleContextLost;
  12089. },
  12090. set: function (value) {
  12091. this._doNotHandleContextLost = value;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12097. /**
  12098. * Gets the performance monitor attached to this engine
  12099. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12100. */
  12101. get: function () {
  12102. return this._performanceMonitor;
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12108. /**
  12109. * Gets the list of texture formats supported
  12110. */
  12111. get: function () {
  12112. return this._texturesSupported;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12118. /**
  12119. * Gets the list of texture formats in use
  12120. */
  12121. get: function () {
  12122. return this._textureFormatInUse;
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(Engine.prototype, "currentViewport", {
  12128. /**
  12129. * Gets the current viewport
  12130. */
  12131. get: function () {
  12132. return this._cachedViewport;
  12133. },
  12134. enumerable: true,
  12135. configurable: true
  12136. });
  12137. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12138. /**
  12139. * Gets the default empty texture
  12140. */
  12141. get: function () {
  12142. if (!this._emptyTexture) {
  12143. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12144. }
  12145. return this._emptyTexture;
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12151. /**
  12152. * Gets the default empty 3D texture
  12153. */
  12154. get: function () {
  12155. if (!this._emptyTexture3D) {
  12156. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12157. }
  12158. return this._emptyTexture3D;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12164. /**
  12165. * Gets the default empty cube texture
  12166. */
  12167. get: function () {
  12168. if (!this._emptyCubeTexture) {
  12169. var faceData = new Uint8Array(4);
  12170. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12171. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12172. }
  12173. return this._emptyCubeTexture;
  12174. },
  12175. enumerable: true,
  12176. configurable: true
  12177. });
  12178. Engine.prototype._rebuildInternalTextures = function () {
  12179. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12180. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12181. var internalTexture = currentState_1[_i];
  12182. internalTexture._rebuild();
  12183. }
  12184. };
  12185. Engine.prototype._rebuildEffects = function () {
  12186. for (var key in this._compiledEffects) {
  12187. var effect = this._compiledEffects[key];
  12188. effect._prepareEffect();
  12189. }
  12190. BABYLON.Effect.ResetCache();
  12191. };
  12192. Engine.prototype._rebuildBuffers = function () {
  12193. // Index / Vertex
  12194. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12195. var scene = _a[_i];
  12196. scene.resetCachedMaterial();
  12197. scene._rebuildGeometries();
  12198. scene._rebuildTextures();
  12199. }
  12200. // Uniforms
  12201. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12202. var uniformBuffer = _c[_b];
  12203. uniformBuffer._rebuild();
  12204. }
  12205. };
  12206. Engine.prototype._initGLContext = function () {
  12207. // Caps
  12208. this._caps = new EngineCapabilities();
  12209. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12210. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12211. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12212. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12213. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12214. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12215. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12216. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12217. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12218. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12219. // Infos
  12220. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12221. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12222. if (rendererInfo != null) {
  12223. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12224. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12225. }
  12226. if (!this._glVendor) {
  12227. this._glVendor = "Unknown vendor";
  12228. }
  12229. if (!this._glRenderer) {
  12230. this._glRenderer = "Unknown renderer";
  12231. }
  12232. // Constants
  12233. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12234. if (this._gl.RGBA16F !== 0x881A) {
  12235. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12236. }
  12237. if (this._gl.RGBA32F !== 0x8814) {
  12238. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12239. }
  12240. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12241. this._gl.DEPTH24_STENCIL8 = 35056;
  12242. }
  12243. // Extensions
  12244. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12245. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12246. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12247. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12248. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12249. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12250. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12251. 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');
  12252. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12253. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12254. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12255. this._caps.highPrecisionShaderSupported = true;
  12256. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12257. if (this._caps.timerQuery) {
  12258. if (this._webGLVersion === 1) {
  12259. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12260. }
  12261. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12262. }
  12263. // Checks if some of the format renders first to allow the use of webgl inspector.
  12264. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12265. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12266. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12267. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12268. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12269. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12270. if (this._webGLVersion > 1) {
  12271. this._gl.HALF_FLOAT_OES = 0x140B;
  12272. }
  12273. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12274. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12275. // Draw buffers
  12276. if (this._webGLVersion > 1) {
  12277. this._caps.drawBuffersExtension = true;
  12278. }
  12279. else {
  12280. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12281. if (drawBuffersExtension !== null) {
  12282. this._caps.drawBuffersExtension = true;
  12283. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12284. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12285. for (var i = 0; i < 16; i++) {
  12286. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12287. }
  12288. }
  12289. else {
  12290. this._caps.drawBuffersExtension = false;
  12291. }
  12292. }
  12293. // Depth Texture
  12294. if (this._webGLVersion > 1) {
  12295. this._caps.depthTextureExtension = true;
  12296. }
  12297. else {
  12298. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12299. if (depthTextureExtension != null) {
  12300. this._caps.depthTextureExtension = true;
  12301. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12302. }
  12303. }
  12304. // Vertex array object
  12305. if (this._webGLVersion > 1) {
  12306. this._caps.vertexArrayObject = true;
  12307. }
  12308. else {
  12309. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12310. if (vertexArrayObjectExtension != null) {
  12311. this._caps.vertexArrayObject = true;
  12312. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12313. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12314. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12315. }
  12316. else {
  12317. this._caps.vertexArrayObject = false;
  12318. }
  12319. }
  12320. // Instances count
  12321. if (this._webGLVersion > 1) {
  12322. this._caps.instancedArrays = true;
  12323. }
  12324. else {
  12325. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12326. if (instanceExtension != null) {
  12327. this._caps.instancedArrays = true;
  12328. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12329. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12330. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12331. }
  12332. else {
  12333. this._caps.instancedArrays = false;
  12334. }
  12335. }
  12336. // Intelligently add supported compressed formats in order to check for.
  12337. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12338. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12339. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12340. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12341. if (this._caps.astc)
  12342. this.texturesSupported.push('-astc.ktx');
  12343. if (this._caps.s3tc)
  12344. this.texturesSupported.push('-dxt.ktx');
  12345. if (this._caps.pvrtc)
  12346. this.texturesSupported.push('-pvrtc.ktx');
  12347. if (this._caps.etc2)
  12348. this.texturesSupported.push('-etc2.ktx');
  12349. if (this._caps.etc1)
  12350. this.texturesSupported.push('-etc1.ktx');
  12351. if (this._gl.getShaderPrecisionFormat) {
  12352. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12353. if (highp) {
  12354. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12355. }
  12356. }
  12357. // Depth buffer
  12358. this.setDepthBuffer(true);
  12359. this.setDepthFunctionToLessOrEqual();
  12360. this.setDepthWrite(true);
  12361. // Texture maps
  12362. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12363. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12364. this._nextFreeTextureSlots.push(slot);
  12365. }
  12366. };
  12367. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12368. /**
  12369. * Gets version of the current webGL context
  12370. */
  12371. get: function () {
  12372. return this._webGLVersion;
  12373. },
  12374. enumerable: true,
  12375. configurable: true
  12376. });
  12377. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12378. /**
  12379. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12380. */
  12381. get: function () {
  12382. return this._isStencilEnable;
  12383. },
  12384. enumerable: true,
  12385. configurable: true
  12386. });
  12387. Engine.prototype._prepareWorkingCanvas = function () {
  12388. if (this._workingCanvas) {
  12389. return;
  12390. }
  12391. this._workingCanvas = document.createElement("canvas");
  12392. var context = this._workingCanvas.getContext("2d");
  12393. if (context) {
  12394. this._workingContext = context;
  12395. }
  12396. };
  12397. /**
  12398. * Reset the texture cache to empty state
  12399. */
  12400. Engine.prototype.resetTextureCache = function () {
  12401. for (var key in this._boundTexturesCache) {
  12402. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12403. continue;
  12404. }
  12405. var boundTexture = this._boundTexturesCache[key];
  12406. if (boundTexture) {
  12407. this._removeDesignatedSlot(boundTexture);
  12408. }
  12409. this._boundTexturesCache[key] = null;
  12410. }
  12411. if (!this.disableTextureBindingOptimization) {
  12412. this._nextFreeTextureSlots = [];
  12413. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12414. this._nextFreeTextureSlots.push(slot);
  12415. }
  12416. }
  12417. this._currentTextureChannel = -1;
  12418. };
  12419. /**
  12420. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12421. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12422. * @returns true if engine is in deterministic lock step mode
  12423. */
  12424. Engine.prototype.isDeterministicLockStep = function () {
  12425. return this._deterministicLockstep;
  12426. };
  12427. /**
  12428. * Gets the max steps when engine is running in deterministic lock step
  12429. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12430. * @returns the max steps
  12431. */
  12432. Engine.prototype.getLockstepMaxSteps = function () {
  12433. return this._lockstepMaxSteps;
  12434. };
  12435. /**
  12436. * Gets an object containing information about the current webGL context
  12437. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12438. */
  12439. Engine.prototype.getGlInfo = function () {
  12440. return {
  12441. vendor: this._glVendor,
  12442. renderer: this._glRenderer,
  12443. version: this._glVersion
  12444. };
  12445. };
  12446. /**
  12447. * Gets current aspect ratio
  12448. * @param camera defines the camera to use to get the aspect ratio
  12449. * @param useScreen defines if screen size must be used (or the current render target if any)
  12450. * @returns a number defining the aspect ratio
  12451. */
  12452. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12453. if (useScreen === void 0) { useScreen = false; }
  12454. var viewport = camera.viewport;
  12455. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12456. };
  12457. /**
  12458. * Gets current screen aspect ratio
  12459. * @returns a number defining the aspect ratio
  12460. */
  12461. Engine.prototype.getScreenAspectRatio = function () {
  12462. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12463. };
  12464. /**
  12465. * Gets the current render width
  12466. * @param useScreen defines if screen size must be used (or the current render target if any)
  12467. * @returns a number defining the current render width
  12468. */
  12469. Engine.prototype.getRenderWidth = function (useScreen) {
  12470. if (useScreen === void 0) { useScreen = false; }
  12471. if (!useScreen && this._currentRenderTarget) {
  12472. return this._currentRenderTarget.width;
  12473. }
  12474. return this._gl.drawingBufferWidth;
  12475. };
  12476. /**
  12477. * Gets the current render height
  12478. * @param useScreen defines if screen size must be used (or the current render target if any)
  12479. * @returns a number defining the current render height
  12480. */
  12481. Engine.prototype.getRenderHeight = function (useScreen) {
  12482. if (useScreen === void 0) { useScreen = false; }
  12483. if (!useScreen && this._currentRenderTarget) {
  12484. return this._currentRenderTarget.height;
  12485. }
  12486. return this._gl.drawingBufferHeight;
  12487. };
  12488. /**
  12489. * Gets the HTML canvas attached with the current webGL context
  12490. * @returns a HTML canvas
  12491. */
  12492. Engine.prototype.getRenderingCanvas = function () {
  12493. return this._renderingCanvas;
  12494. };
  12495. /**
  12496. * Gets the client rect of the HTML canvas attached with the current webGL context
  12497. * @returns a client rectanglee
  12498. */
  12499. Engine.prototype.getRenderingCanvasClientRect = function () {
  12500. if (!this._renderingCanvas) {
  12501. return null;
  12502. }
  12503. return this._renderingCanvas.getBoundingClientRect();
  12504. };
  12505. /**
  12506. * Defines the hardware scaling level.
  12507. * By default the hardware scaling level is computed from the window device ratio.
  12508. * 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.
  12509. * @param level defines the level to use
  12510. */
  12511. Engine.prototype.setHardwareScalingLevel = function (level) {
  12512. this._hardwareScalingLevel = level;
  12513. this.resize();
  12514. };
  12515. /**
  12516. * Gets the current hardware scaling level.
  12517. * By default the hardware scaling level is computed from the window device ratio.
  12518. * 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.
  12519. * @returns a number indicating the current hardware scaling level
  12520. */
  12521. Engine.prototype.getHardwareScalingLevel = function () {
  12522. return this._hardwareScalingLevel;
  12523. };
  12524. /**
  12525. * Gets the list of loaded textures
  12526. * @returns an array containing all loaded textures
  12527. */
  12528. Engine.prototype.getLoadedTexturesCache = function () {
  12529. return this._internalTexturesCache;
  12530. };
  12531. /**
  12532. * Gets the object containing all engine capabilities
  12533. * @returns the EngineCapabilities object
  12534. */
  12535. Engine.prototype.getCaps = function () {
  12536. return this._caps;
  12537. };
  12538. Object.defineProperty(Engine.prototype, "drawCalls", {
  12539. /** @hidden */
  12540. get: function () {
  12541. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12542. return 0;
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12548. /** @hidden */
  12549. get: function () {
  12550. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12551. return null;
  12552. },
  12553. enumerable: true,
  12554. configurable: true
  12555. });
  12556. /**
  12557. * Gets the current depth function
  12558. * @returns a number defining the depth function
  12559. */
  12560. Engine.prototype.getDepthFunction = function () {
  12561. return this._depthCullingState.depthFunc;
  12562. };
  12563. /**
  12564. * Sets the current depth function
  12565. * @param depthFunc defines the function to use
  12566. */
  12567. Engine.prototype.setDepthFunction = function (depthFunc) {
  12568. this._depthCullingState.depthFunc = depthFunc;
  12569. };
  12570. /**
  12571. * Sets the current depth function to GREATER
  12572. */
  12573. Engine.prototype.setDepthFunctionToGreater = function () {
  12574. this._depthCullingState.depthFunc = this._gl.GREATER;
  12575. };
  12576. /**
  12577. * Sets the current depth function to GEQUAL
  12578. */
  12579. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12580. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12581. };
  12582. /**
  12583. * Sets the current depth function to LESS
  12584. */
  12585. Engine.prototype.setDepthFunctionToLess = function () {
  12586. this._depthCullingState.depthFunc = this._gl.LESS;
  12587. };
  12588. /**
  12589. * Sets the current depth function to LEQUAL
  12590. */
  12591. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12592. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12593. };
  12594. /**
  12595. * Gets a boolean indicating if stencil buffer is enabled
  12596. * @returns the current stencil buffer state
  12597. */
  12598. Engine.prototype.getStencilBuffer = function () {
  12599. return this._stencilState.stencilTest;
  12600. };
  12601. /**
  12602. * Enable or disable the stencil buffer
  12603. * @param enable defines if the stencil buffer must be enabled or disabled
  12604. */
  12605. Engine.prototype.setStencilBuffer = function (enable) {
  12606. this._stencilState.stencilTest = enable;
  12607. };
  12608. /**
  12609. * Gets the current stencil mask
  12610. * @returns a number defining the new stencil mask to use
  12611. */
  12612. Engine.prototype.getStencilMask = function () {
  12613. return this._stencilState.stencilMask;
  12614. };
  12615. /**
  12616. * Sets the current stencil mask
  12617. * @param mask defines the new stencil mask to use
  12618. */
  12619. Engine.prototype.setStencilMask = function (mask) {
  12620. this._stencilState.stencilMask = mask;
  12621. };
  12622. /**
  12623. * Gets the current stencil function
  12624. * @returns a number defining the stencil function to use
  12625. */
  12626. Engine.prototype.getStencilFunction = function () {
  12627. return this._stencilState.stencilFunc;
  12628. };
  12629. /**
  12630. * Gets the current stencil reference value
  12631. * @returns a number defining the stencil reference value to use
  12632. */
  12633. Engine.prototype.getStencilFunctionReference = function () {
  12634. return this._stencilState.stencilFuncRef;
  12635. };
  12636. /**
  12637. * Gets the current stencil mask
  12638. * @returns a number defining the stencil mask to use
  12639. */
  12640. Engine.prototype.getStencilFunctionMask = function () {
  12641. return this._stencilState.stencilFuncMask;
  12642. };
  12643. /**
  12644. * Sets the current stencil function
  12645. * @param stencilFunc defines the new stencil function to use
  12646. */
  12647. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12648. this._stencilState.stencilFunc = stencilFunc;
  12649. };
  12650. /**
  12651. * Sets the current stencil reference
  12652. * @param reference defines the new stencil reference to use
  12653. */
  12654. Engine.prototype.setStencilFunctionReference = function (reference) {
  12655. this._stencilState.stencilFuncRef = reference;
  12656. };
  12657. /**
  12658. * Sets the current stencil mask
  12659. * @param mask defines the new stencil mask to use
  12660. */
  12661. Engine.prototype.setStencilFunctionMask = function (mask) {
  12662. this._stencilState.stencilFuncMask = mask;
  12663. };
  12664. /**
  12665. * Gets the current stencil operation when stencil fails
  12666. * @returns a number defining stencil operation to use when stencil fails
  12667. */
  12668. Engine.prototype.getStencilOperationFail = function () {
  12669. return this._stencilState.stencilOpStencilFail;
  12670. };
  12671. /**
  12672. * Gets the current stencil operation when depth fails
  12673. * @returns a number defining stencil operation to use when depth fails
  12674. */
  12675. Engine.prototype.getStencilOperationDepthFail = function () {
  12676. return this._stencilState.stencilOpDepthFail;
  12677. };
  12678. /**
  12679. * Gets the current stencil operation when stencil passes
  12680. * @returns a number defining stencil operation to use when stencil passes
  12681. */
  12682. Engine.prototype.getStencilOperationPass = function () {
  12683. return this._stencilState.stencilOpStencilDepthPass;
  12684. };
  12685. /**
  12686. * Sets the stencil operation to use when stencil fails
  12687. * @param operation defines the stencil operation to use when stencil fails
  12688. */
  12689. Engine.prototype.setStencilOperationFail = function (operation) {
  12690. this._stencilState.stencilOpStencilFail = operation;
  12691. };
  12692. /**
  12693. * Sets the stencil operation to use when depth fails
  12694. * @param operation defines the stencil operation to use when depth fails
  12695. */
  12696. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12697. this._stencilState.stencilOpDepthFail = operation;
  12698. };
  12699. /**
  12700. * Sets the stencil operation to use when stencil passes
  12701. * @param operation defines the stencil operation to use when stencil passes
  12702. */
  12703. Engine.prototype.setStencilOperationPass = function (operation) {
  12704. this._stencilState.stencilOpStencilDepthPass = operation;
  12705. };
  12706. /**
  12707. * Sets a boolean indicating if the dithering state is enabled or disabled
  12708. * @param value defines the dithering state
  12709. */
  12710. Engine.prototype.setDitheringState = function (value) {
  12711. if (value) {
  12712. this._gl.enable(this._gl.DITHER);
  12713. }
  12714. else {
  12715. this._gl.disable(this._gl.DITHER);
  12716. }
  12717. };
  12718. /**
  12719. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12720. * @param value defines the rasterizer state
  12721. */
  12722. Engine.prototype.setRasterizerState = function (value) {
  12723. if (value) {
  12724. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12725. }
  12726. else {
  12727. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12728. }
  12729. };
  12730. /**
  12731. * stop executing a render loop function and remove it from the execution array
  12732. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12733. */
  12734. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12735. if (!renderFunction) {
  12736. this._activeRenderLoops = [];
  12737. return;
  12738. }
  12739. var index = this._activeRenderLoops.indexOf(renderFunction);
  12740. if (index >= 0) {
  12741. this._activeRenderLoops.splice(index, 1);
  12742. }
  12743. };
  12744. /** @hidden */
  12745. Engine.prototype._renderLoop = function () {
  12746. if (!this._contextWasLost) {
  12747. var shouldRender = true;
  12748. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12749. shouldRender = false;
  12750. }
  12751. if (shouldRender) {
  12752. // Start new frame
  12753. this.beginFrame();
  12754. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12755. var renderFunction = this._activeRenderLoops[index];
  12756. renderFunction();
  12757. }
  12758. // Present
  12759. this.endFrame();
  12760. }
  12761. }
  12762. if (this._activeRenderLoops.length > 0) {
  12763. // Register new frame
  12764. var requester = null;
  12765. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12766. requester = this._vrDisplay;
  12767. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12768. }
  12769. else {
  12770. this._renderingQueueLaunched = false;
  12771. }
  12772. };
  12773. /**
  12774. * Register and execute a render loop. The engine can have more than one render function
  12775. * @param renderFunction defines the function to continuously execute
  12776. */
  12777. Engine.prototype.runRenderLoop = function (renderFunction) {
  12778. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12779. return;
  12780. }
  12781. this._activeRenderLoops.push(renderFunction);
  12782. if (!this._renderingQueueLaunched) {
  12783. this._renderingQueueLaunched = true;
  12784. this._bindedRenderFunction = this._renderLoop.bind(this);
  12785. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12786. }
  12787. };
  12788. /**
  12789. * Toggle full screen mode
  12790. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12791. * @param options defines an option object to be sent to the requestFullscreen function
  12792. */
  12793. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12794. if (this.isFullscreen) {
  12795. BABYLON.Tools.ExitFullscreen();
  12796. }
  12797. else {
  12798. this._pointerLockRequested = requestPointerLock;
  12799. if (this._renderingCanvas) {
  12800. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12801. }
  12802. }
  12803. };
  12804. /**
  12805. * Clear the current render buffer or the current render target (if any is set up)
  12806. * @param color defines the color to use
  12807. * @param backBuffer defines if the back buffer must be cleared
  12808. * @param depth defines if the depth buffer must be cleared
  12809. * @param stencil defines if the stencil buffer must be cleared
  12810. */
  12811. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12812. if (stencil === void 0) { stencil = false; }
  12813. this.applyStates();
  12814. var mode = 0;
  12815. if (backBuffer && color) {
  12816. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12817. mode |= this._gl.COLOR_BUFFER_BIT;
  12818. }
  12819. if (depth) {
  12820. this._gl.clearDepth(1.0);
  12821. mode |= this._gl.DEPTH_BUFFER_BIT;
  12822. }
  12823. if (stencil) {
  12824. this._gl.clearStencil(0);
  12825. mode |= this._gl.STENCIL_BUFFER_BIT;
  12826. }
  12827. this._gl.clear(mode);
  12828. };
  12829. /**
  12830. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12831. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12832. * @param y defines the y-coordinate of the corner of the clear rectangle
  12833. * @param width defines the width of the clear rectangle
  12834. * @param height defines the height of the clear rectangle
  12835. * @param clearColor defines the clear color
  12836. */
  12837. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12838. var gl = this._gl;
  12839. // Save state
  12840. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12841. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12842. // Change state
  12843. gl.enable(gl.SCISSOR_TEST);
  12844. gl.scissor(x, y, width, height);
  12845. // Clear
  12846. this.clear(clearColor, true, true, true);
  12847. // Restore state
  12848. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12849. if (curScissor === true) {
  12850. gl.enable(gl.SCISSOR_TEST);
  12851. }
  12852. else {
  12853. gl.disable(gl.SCISSOR_TEST);
  12854. }
  12855. };
  12856. /**
  12857. * Set the WebGL's viewport
  12858. * @param viewport defines the viewport element to be used
  12859. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12860. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12861. */
  12862. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12863. var width = requiredWidth || this.getRenderWidth();
  12864. var height = requiredHeight || this.getRenderHeight();
  12865. var x = viewport.x || 0;
  12866. var y = viewport.y || 0;
  12867. this._cachedViewport = viewport;
  12868. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12869. };
  12870. /**
  12871. * Directly set the WebGL Viewport
  12872. * @param x defines the x coordinate of the viewport (in screen space)
  12873. * @param y defines the y coordinate of the viewport (in screen space)
  12874. * @param width defines the width of the viewport (in screen space)
  12875. * @param height defines the height of the viewport (in screen space)
  12876. * @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
  12877. */
  12878. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12879. var currentViewport = this._cachedViewport;
  12880. this._cachedViewport = null;
  12881. this._gl.viewport(x, y, width, height);
  12882. return currentViewport;
  12883. };
  12884. /**
  12885. * Begin a new frame
  12886. */
  12887. Engine.prototype.beginFrame = function () {
  12888. this.onBeginFrameObservable.notifyObservers(this);
  12889. this._measureFps();
  12890. };
  12891. /**
  12892. * Enf the current frame
  12893. */
  12894. Engine.prototype.endFrame = function () {
  12895. // Force a flush in case we are using a bad OS.
  12896. if (this._badOS) {
  12897. this.flushFramebuffer();
  12898. }
  12899. // Submit frame to the vr device, if enabled
  12900. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12901. // TODO: We should only submit the frame if we read frameData successfully.
  12902. this._vrDisplay.submitFrame();
  12903. }
  12904. this.onEndFrameObservable.notifyObservers(this);
  12905. };
  12906. /**
  12907. * Resize the view according to the canvas' size
  12908. */
  12909. Engine.prototype.resize = function () {
  12910. // We're not resizing the size of the canvas while in VR mode & presenting
  12911. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12912. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12913. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12914. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12915. }
  12916. };
  12917. /**
  12918. * Force a specific size of the canvas
  12919. * @param width defines the new canvas' width
  12920. * @param height defines the new canvas' height
  12921. */
  12922. Engine.prototype.setSize = function (width, height) {
  12923. if (!this._renderingCanvas) {
  12924. return;
  12925. }
  12926. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12927. return;
  12928. }
  12929. this._renderingCanvas.width = width;
  12930. this._renderingCanvas.height = height;
  12931. for (var index = 0; index < this.scenes.length; index++) {
  12932. var scene = this.scenes[index];
  12933. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12934. var cam = scene.cameras[camIndex];
  12935. cam._currentRenderId = 0;
  12936. }
  12937. }
  12938. if (this.onResizeObservable.hasObservers) {
  12939. this.onResizeObservable.notifyObservers(this);
  12940. }
  12941. };
  12942. // WebVR functions
  12943. /**
  12944. * Gets a boolean indicating if a webVR device was detected
  12945. * @returns true if a webVR device was detected
  12946. */
  12947. Engine.prototype.isVRDevicePresent = function () {
  12948. return !!this._vrDisplay;
  12949. };
  12950. /**
  12951. * Gets the current webVR device
  12952. * @returns the current webVR device (or null)
  12953. */
  12954. Engine.prototype.getVRDevice = function () {
  12955. return this._vrDisplay;
  12956. };
  12957. /**
  12958. * Initializes a webVR display and starts listening to display change events
  12959. * The onVRDisplayChangedObservable will be notified upon these changes
  12960. * @returns The onVRDisplayChangedObservable
  12961. */
  12962. Engine.prototype.initWebVR = function () {
  12963. this.initWebVRAsync();
  12964. return this.onVRDisplayChangedObservable;
  12965. };
  12966. /**
  12967. * Initializes a webVR display and starts listening to display change events
  12968. * The onVRDisplayChangedObservable will be notified upon these changes
  12969. * @returns A promise containing a VRDisplay and if vr is supported
  12970. */
  12971. Engine.prototype.initWebVRAsync = function () {
  12972. var _this = this;
  12973. var notifyObservers = function () {
  12974. var eventArgs = {
  12975. vrDisplay: _this._vrDisplay,
  12976. vrSupported: _this._vrSupported
  12977. };
  12978. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12979. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12980. };
  12981. if (!this._onVrDisplayConnect) {
  12982. this._onVrDisplayConnect = function (event) {
  12983. _this._vrDisplay = event.display;
  12984. notifyObservers();
  12985. };
  12986. this._onVrDisplayDisconnect = function () {
  12987. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12988. _this._vrDisplay = undefined;
  12989. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12990. notifyObservers();
  12991. };
  12992. this._onVrDisplayPresentChange = function () {
  12993. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12994. };
  12995. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12996. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12997. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12998. }
  12999. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13000. this._webVRInitPromise.then(notifyObservers);
  13001. return this._webVRInitPromise;
  13002. };
  13003. /**
  13004. * Call this function to switch to webVR mode
  13005. * Will do nothing if webVR is not supported or if there is no webVR device
  13006. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13007. */
  13008. Engine.prototype.enableVR = function () {
  13009. var _this = this;
  13010. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13011. var onResolved = function () {
  13012. _this.onVRRequestPresentComplete.notifyObservers(true);
  13013. _this._onVRFullScreenTriggered();
  13014. };
  13015. var onRejected = function () {
  13016. _this.onVRRequestPresentComplete.notifyObservers(false);
  13017. };
  13018. this.onVRRequestPresentStart.notifyObservers(this);
  13019. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13020. }
  13021. };
  13022. /**
  13023. * Call this function to leave webVR mode
  13024. * Will do nothing if webVR is not supported or if there is no webVR device
  13025. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13026. */
  13027. Engine.prototype.disableVR = function () {
  13028. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13029. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13030. }
  13031. };
  13032. Engine.prototype._getVRDisplaysAsync = function () {
  13033. var _this = this;
  13034. return new Promise(function (res, rej) {
  13035. if (navigator.getVRDisplays) {
  13036. navigator.getVRDisplays().then(function (devices) {
  13037. _this._vrSupported = true;
  13038. // note that devices may actually be an empty array. This is fine;
  13039. // we expect this._vrDisplay to be undefined in this case.
  13040. _this._vrDisplay = devices[0];
  13041. res({
  13042. vrDisplay: _this._vrDisplay,
  13043. vrSupported: _this._vrSupported
  13044. });
  13045. });
  13046. }
  13047. else {
  13048. _this._vrDisplay = undefined;
  13049. _this._vrSupported = false;
  13050. res({
  13051. vrDisplay: _this._vrDisplay,
  13052. vrSupported: _this._vrSupported
  13053. });
  13054. }
  13055. });
  13056. };
  13057. /**
  13058. * Binds the frame buffer to the specified texture.
  13059. * @param texture The texture to render to or null for the default canvas
  13060. * @param faceIndex The face of the texture to render to in case of cube texture
  13061. * @param requiredWidth The width of the target to render to
  13062. * @param requiredHeight The height of the target to render to
  13063. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13064. * @param depthStencilTexture The depth stencil texture to use to render
  13065. */
  13066. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13067. if (this._currentRenderTarget) {
  13068. this.unBindFramebuffer(this._currentRenderTarget);
  13069. }
  13070. this._currentRenderTarget = texture;
  13071. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13072. var gl = this._gl;
  13073. if (texture.isCube) {
  13074. if (faceIndex === undefined) {
  13075. faceIndex = 0;
  13076. }
  13077. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13078. if (depthStencilTexture) {
  13079. if (depthStencilTexture._generateStencilBuffer) {
  13080. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13081. }
  13082. else {
  13083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13084. }
  13085. }
  13086. }
  13087. if (this._cachedViewport && !forceFullscreenViewport) {
  13088. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13089. }
  13090. else {
  13091. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13092. }
  13093. this.wipeCaches();
  13094. };
  13095. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13096. if (this._currentFramebuffer !== framebuffer) {
  13097. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13098. this._currentFramebuffer = framebuffer;
  13099. }
  13100. };
  13101. /**
  13102. * Unbind the current render target texture from the webGL context
  13103. * @param texture defines the render target texture to unbind
  13104. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13105. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13106. */
  13107. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13108. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13109. this._currentRenderTarget = null;
  13110. // If MSAA, we need to bitblt back to main texture
  13111. var gl = this._gl;
  13112. if (texture._MSAAFramebuffer) {
  13113. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13114. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13115. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13116. }
  13117. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13118. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13119. gl.generateMipmap(gl.TEXTURE_2D);
  13120. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13121. }
  13122. if (onBeforeUnbind) {
  13123. if (texture._MSAAFramebuffer) {
  13124. // Bind the correct framebuffer
  13125. this.bindUnboundFramebuffer(texture._framebuffer);
  13126. }
  13127. onBeforeUnbind();
  13128. }
  13129. this.bindUnboundFramebuffer(null);
  13130. };
  13131. /**
  13132. * Unbind a list of render target textures from the webGL context
  13133. * This is used only when drawBuffer extension or webGL2 are active
  13134. * @param textures defines the render target textures to unbind
  13135. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13136. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13137. */
  13138. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13139. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13140. this._currentRenderTarget = null;
  13141. // If MSAA, we need to bitblt back to main texture
  13142. var gl = this._gl;
  13143. if (textures[0]._MSAAFramebuffer) {
  13144. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13145. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13146. var attachments = textures[0]._attachments;
  13147. if (!attachments) {
  13148. attachments = new Array(textures.length);
  13149. textures[0]._attachments = attachments;
  13150. }
  13151. for (var i = 0; i < textures.length; i++) {
  13152. var texture = textures[i];
  13153. for (var j = 0; j < attachments.length; j++) {
  13154. attachments[j] = gl.NONE;
  13155. }
  13156. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13157. gl.readBuffer(attachments[i]);
  13158. gl.drawBuffers(attachments);
  13159. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13160. }
  13161. for (var i = 0; i < attachments.length; i++) {
  13162. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13163. }
  13164. gl.drawBuffers(attachments);
  13165. }
  13166. for (var i = 0; i < textures.length; i++) {
  13167. var texture = textures[i];
  13168. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13169. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13170. gl.generateMipmap(gl.TEXTURE_2D);
  13171. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13172. }
  13173. }
  13174. if (onBeforeUnbind) {
  13175. if (textures[0]._MSAAFramebuffer) {
  13176. // Bind the correct framebuffer
  13177. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13178. }
  13179. onBeforeUnbind();
  13180. }
  13181. this.bindUnboundFramebuffer(null);
  13182. };
  13183. /**
  13184. * Force the mipmap generation for the given render target texture
  13185. * @param texture defines the render target texture to use
  13186. */
  13187. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13188. if (texture.generateMipMaps) {
  13189. var gl = this._gl;
  13190. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13191. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13192. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13193. }
  13194. };
  13195. /**
  13196. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13197. */
  13198. Engine.prototype.flushFramebuffer = function () {
  13199. this._gl.flush();
  13200. };
  13201. /**
  13202. * Unbind the current render target and bind the default framebuffer
  13203. */
  13204. Engine.prototype.restoreDefaultFramebuffer = function () {
  13205. if (this._currentRenderTarget) {
  13206. this.unBindFramebuffer(this._currentRenderTarget);
  13207. }
  13208. else {
  13209. this.bindUnboundFramebuffer(null);
  13210. }
  13211. if (this._cachedViewport) {
  13212. this.setViewport(this._cachedViewport);
  13213. }
  13214. this.wipeCaches();
  13215. };
  13216. // UBOs
  13217. /**
  13218. * Create an uniform buffer
  13219. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13220. * @param elements defines the content of the uniform buffer
  13221. * @returns the webGL uniform buffer
  13222. */
  13223. Engine.prototype.createUniformBuffer = function (elements) {
  13224. var ubo = this._gl.createBuffer();
  13225. if (!ubo) {
  13226. throw new Error("Unable to create uniform buffer");
  13227. }
  13228. this.bindUniformBuffer(ubo);
  13229. if (elements instanceof Float32Array) {
  13230. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13231. }
  13232. else {
  13233. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13234. }
  13235. this.bindUniformBuffer(null);
  13236. ubo.references = 1;
  13237. return ubo;
  13238. };
  13239. /**
  13240. * Create a dynamic uniform buffer
  13241. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13242. * @param elements defines the content of the uniform buffer
  13243. * @returns the webGL uniform buffer
  13244. */
  13245. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13246. var ubo = this._gl.createBuffer();
  13247. if (!ubo) {
  13248. throw new Error("Unable to create dynamic uniform buffer");
  13249. }
  13250. this.bindUniformBuffer(ubo);
  13251. if (elements instanceof Float32Array) {
  13252. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13253. }
  13254. else {
  13255. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13256. }
  13257. this.bindUniformBuffer(null);
  13258. ubo.references = 1;
  13259. return ubo;
  13260. };
  13261. /**
  13262. * Update an existing uniform buffer
  13263. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13264. * @param uniformBuffer defines the target uniform buffer
  13265. * @param elements defines the content to update
  13266. * @param offset defines the offset in the uniform buffer where update should start
  13267. * @param count defines the size of the data to update
  13268. */
  13269. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13270. this.bindUniformBuffer(uniformBuffer);
  13271. if (offset === undefined) {
  13272. offset = 0;
  13273. }
  13274. if (count === undefined) {
  13275. if (elements instanceof Float32Array) {
  13276. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13277. }
  13278. else {
  13279. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13280. }
  13281. }
  13282. else {
  13283. if (elements instanceof Float32Array) {
  13284. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13285. }
  13286. else {
  13287. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13288. }
  13289. }
  13290. this.bindUniformBuffer(null);
  13291. };
  13292. // VBOs
  13293. Engine.prototype._resetVertexBufferBinding = function () {
  13294. this.bindArrayBuffer(null);
  13295. this._cachedVertexBuffers = null;
  13296. };
  13297. /**
  13298. * Creates a vertex buffer
  13299. * @param data the data for the vertex buffer
  13300. * @returns the new WebGL static buffer
  13301. */
  13302. Engine.prototype.createVertexBuffer = function (data) {
  13303. var vbo = this._gl.createBuffer();
  13304. if (!vbo) {
  13305. throw new Error("Unable to create vertex buffer");
  13306. }
  13307. this.bindArrayBuffer(vbo);
  13308. if (data instanceof Array) {
  13309. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13310. }
  13311. else {
  13312. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13313. }
  13314. this._resetVertexBufferBinding();
  13315. vbo.references = 1;
  13316. return vbo;
  13317. };
  13318. /**
  13319. * Creates a dynamic vertex buffer
  13320. * @param data the data for the dynamic vertex buffer
  13321. * @returns the new WebGL dynamic buffer
  13322. */
  13323. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13324. var vbo = this._gl.createBuffer();
  13325. if (!vbo) {
  13326. throw new Error("Unable to create dynamic vertex buffer");
  13327. }
  13328. this.bindArrayBuffer(vbo);
  13329. if (data instanceof Array) {
  13330. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13331. }
  13332. else {
  13333. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13334. }
  13335. this._resetVertexBufferBinding();
  13336. vbo.references = 1;
  13337. return vbo;
  13338. };
  13339. /**
  13340. * Update a dynamic index buffer
  13341. * @param indexBuffer defines the target index buffer
  13342. * @param indices defines the data to update
  13343. * @param offset defines the offset in the target index buffer where update should start
  13344. */
  13345. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13346. if (offset === void 0) { offset = 0; }
  13347. // Force cache update
  13348. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13349. this.bindIndexBuffer(indexBuffer);
  13350. var arrayBuffer;
  13351. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13352. arrayBuffer = indices;
  13353. }
  13354. else {
  13355. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13356. }
  13357. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13358. this._resetIndexBufferBinding();
  13359. };
  13360. /**
  13361. * Updates a dynamic vertex buffer.
  13362. * @param vertexBuffer the vertex buffer to update
  13363. * @param data the data used to update the vertex buffer
  13364. * @param byteOffset the byte offset of the data
  13365. * @param byteLength the byte length of the data
  13366. */
  13367. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13368. this.bindArrayBuffer(vertexBuffer);
  13369. if (byteOffset === undefined) {
  13370. byteOffset = 0;
  13371. }
  13372. if (byteLength === undefined) {
  13373. if (data instanceof Array) {
  13374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13375. }
  13376. else {
  13377. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13378. }
  13379. }
  13380. else {
  13381. if (data instanceof Array) {
  13382. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13383. }
  13384. else {
  13385. if (data instanceof ArrayBuffer) {
  13386. data = new Uint8Array(data, byteOffset, byteLength);
  13387. }
  13388. else {
  13389. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13390. }
  13391. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13392. }
  13393. }
  13394. this._resetVertexBufferBinding();
  13395. };
  13396. Engine.prototype._resetIndexBufferBinding = function () {
  13397. this.bindIndexBuffer(null);
  13398. this._cachedIndexBuffer = null;
  13399. };
  13400. /**
  13401. * Creates a new index buffer
  13402. * @param indices defines the content of the index buffer
  13403. * @param updatable defines if the index buffer must be updatable
  13404. * @returns a new webGL buffer
  13405. */
  13406. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13407. var vbo = this._gl.createBuffer();
  13408. if (!vbo) {
  13409. throw new Error("Unable to create index buffer");
  13410. }
  13411. this.bindIndexBuffer(vbo);
  13412. // Check for 32 bits indices
  13413. var arrayBuffer;
  13414. var need32Bits = false;
  13415. if (indices instanceof Uint16Array) {
  13416. arrayBuffer = indices;
  13417. }
  13418. else {
  13419. //check 32 bit support
  13420. if (this._caps.uintIndices) {
  13421. if (indices instanceof Uint32Array) {
  13422. arrayBuffer = indices;
  13423. need32Bits = true;
  13424. }
  13425. else {
  13426. //number[] or Int32Array, check if 32 bit is necessary
  13427. for (var index = 0; index < indices.length; index++) {
  13428. if (indices[index] > 65535) {
  13429. need32Bits = true;
  13430. break;
  13431. }
  13432. }
  13433. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13434. }
  13435. }
  13436. else {
  13437. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13438. arrayBuffer = new Uint16Array(indices);
  13439. }
  13440. }
  13441. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13442. this._resetIndexBufferBinding();
  13443. vbo.references = 1;
  13444. vbo.is32Bits = need32Bits;
  13445. return vbo;
  13446. };
  13447. /**
  13448. * Bind a webGL buffer to the webGL context
  13449. * @param buffer defines the buffer to bind
  13450. */
  13451. Engine.prototype.bindArrayBuffer = function (buffer) {
  13452. if (!this._vaoRecordInProgress) {
  13453. this._unbindVertexArrayObject();
  13454. }
  13455. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13456. };
  13457. /**
  13458. * Bind an uniform buffer to the current webGL context
  13459. * @param buffer defines the buffer to bind
  13460. */
  13461. Engine.prototype.bindUniformBuffer = function (buffer) {
  13462. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13463. };
  13464. /**
  13465. * Bind a buffer to the current webGL context at a given location
  13466. * @param buffer defines the buffer to bind
  13467. * @param location defines the index where to bind the buffer
  13468. */
  13469. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13470. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13471. };
  13472. /**
  13473. * Bind a specific block at a given index in a specific shader program
  13474. * @param shaderProgram defines the shader program
  13475. * @param blockName defines the block name
  13476. * @param index defines the index where to bind the block
  13477. */
  13478. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13479. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13480. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13481. };
  13482. ;
  13483. Engine.prototype.bindIndexBuffer = function (buffer) {
  13484. if (!this._vaoRecordInProgress) {
  13485. this._unbindVertexArrayObject();
  13486. }
  13487. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13488. };
  13489. Engine.prototype.bindBuffer = function (buffer, target) {
  13490. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13491. this._gl.bindBuffer(target, buffer);
  13492. this._currentBoundBuffer[target] = buffer;
  13493. }
  13494. };
  13495. /**
  13496. * update the bound buffer with the given data
  13497. * @param data defines the data to update
  13498. */
  13499. Engine.prototype.updateArrayBuffer = function (data) {
  13500. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13501. };
  13502. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13503. var pointer = this._currentBufferPointers[indx];
  13504. var changed = false;
  13505. if (!pointer.active) {
  13506. changed = true;
  13507. pointer.active = true;
  13508. pointer.index = indx;
  13509. pointer.size = size;
  13510. pointer.type = type;
  13511. pointer.normalized = normalized;
  13512. pointer.stride = stride;
  13513. pointer.offset = offset;
  13514. pointer.buffer = buffer;
  13515. }
  13516. else {
  13517. if (pointer.buffer !== buffer) {
  13518. pointer.buffer = buffer;
  13519. changed = true;
  13520. }
  13521. if (pointer.size !== size) {
  13522. pointer.size = size;
  13523. changed = true;
  13524. }
  13525. if (pointer.type !== type) {
  13526. pointer.type = type;
  13527. changed = true;
  13528. }
  13529. if (pointer.normalized !== normalized) {
  13530. pointer.normalized = normalized;
  13531. changed = true;
  13532. }
  13533. if (pointer.stride !== stride) {
  13534. pointer.stride = stride;
  13535. changed = true;
  13536. }
  13537. if (pointer.offset !== offset) {
  13538. pointer.offset = offset;
  13539. changed = true;
  13540. }
  13541. }
  13542. if (changed || this._vaoRecordInProgress) {
  13543. this.bindArrayBuffer(buffer);
  13544. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13545. }
  13546. };
  13547. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13548. if (indexBuffer == null) {
  13549. return;
  13550. }
  13551. if (this._cachedIndexBuffer !== indexBuffer) {
  13552. this._cachedIndexBuffer = indexBuffer;
  13553. this.bindIndexBuffer(indexBuffer);
  13554. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13555. }
  13556. };
  13557. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13558. var attributes = effect.getAttributesNames();
  13559. if (!this._vaoRecordInProgress) {
  13560. this._unbindVertexArrayObject();
  13561. }
  13562. this.unbindAllAttributes();
  13563. for (var index = 0; index < attributes.length; index++) {
  13564. var order = effect.getAttributeLocation(index);
  13565. if (order >= 0) {
  13566. var vertexBuffer = vertexBuffers[attributes[index]];
  13567. if (!vertexBuffer) {
  13568. continue;
  13569. }
  13570. this._gl.enableVertexAttribArray(order);
  13571. if (!this._vaoRecordInProgress) {
  13572. this._vertexAttribArraysEnabled[order] = true;
  13573. }
  13574. var buffer = vertexBuffer.getBuffer();
  13575. if (buffer) {
  13576. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13577. if (vertexBuffer.getIsInstanced()) {
  13578. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13579. if (!this._vaoRecordInProgress) {
  13580. this._currentInstanceLocations.push(order);
  13581. this._currentInstanceBuffers.push(buffer);
  13582. }
  13583. }
  13584. }
  13585. }
  13586. }
  13587. };
  13588. /**
  13589. * Records a vertex array object
  13590. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13591. * @param vertexBuffers defines the list of vertex buffers to store
  13592. * @param indexBuffer defines the index buffer to store
  13593. * @param effect defines the effect to store
  13594. * @returns the new vertex array object
  13595. */
  13596. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13597. var vao = this._gl.createVertexArray();
  13598. this._vaoRecordInProgress = true;
  13599. this._gl.bindVertexArray(vao);
  13600. this._mustWipeVertexAttributes = true;
  13601. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13602. this.bindIndexBuffer(indexBuffer);
  13603. this._vaoRecordInProgress = false;
  13604. this._gl.bindVertexArray(null);
  13605. return vao;
  13606. };
  13607. /**
  13608. * Bind a specific vertex array object
  13609. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13610. * @param vertexArrayObject defines the vertex array object to bind
  13611. * @param indexBuffer defines the index buffer to bind
  13612. */
  13613. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13614. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13615. this._cachedVertexArrayObject = vertexArrayObject;
  13616. this._gl.bindVertexArray(vertexArrayObject);
  13617. this._cachedVertexBuffers = null;
  13618. this._cachedIndexBuffer = null;
  13619. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13620. this._mustWipeVertexAttributes = true;
  13621. }
  13622. };
  13623. /**
  13624. * Bind webGl buffers directly to the webGL context
  13625. * @param vertexBuffer defines the vertex buffer to bind
  13626. * @param indexBuffer defines the index buffer to bind
  13627. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13628. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13629. * @param effect defines the effect associated with the vertex buffer
  13630. */
  13631. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13632. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13633. this._cachedVertexBuffers = vertexBuffer;
  13634. this._cachedEffectForVertexBuffers = effect;
  13635. var attributesCount = effect.getAttributesCount();
  13636. this._unbindVertexArrayObject();
  13637. this.unbindAllAttributes();
  13638. var offset = 0;
  13639. for (var index = 0; index < attributesCount; index++) {
  13640. if (index < vertexDeclaration.length) {
  13641. var order = effect.getAttributeLocation(index);
  13642. if (order >= 0) {
  13643. this._gl.enableVertexAttribArray(order);
  13644. this._vertexAttribArraysEnabled[order] = true;
  13645. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13646. }
  13647. offset += vertexDeclaration[index] * 4;
  13648. }
  13649. }
  13650. }
  13651. this._bindIndexBufferWithCache(indexBuffer);
  13652. };
  13653. Engine.prototype._unbindVertexArrayObject = function () {
  13654. if (!this._cachedVertexArrayObject) {
  13655. return;
  13656. }
  13657. this._cachedVertexArrayObject = null;
  13658. this._gl.bindVertexArray(null);
  13659. };
  13660. /**
  13661. * Bind a list of vertex buffers to the webGL context
  13662. * @param vertexBuffers defines the list of vertex buffers to bind
  13663. * @param indexBuffer defines the index buffer to bind
  13664. * @param effect defines the effect associated with the vertex buffers
  13665. */
  13666. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13667. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13668. this._cachedVertexBuffers = vertexBuffers;
  13669. this._cachedEffectForVertexBuffers = effect;
  13670. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13671. }
  13672. this._bindIndexBufferWithCache(indexBuffer);
  13673. };
  13674. /**
  13675. * Unbind all instance attributes
  13676. */
  13677. Engine.prototype.unbindInstanceAttributes = function () {
  13678. var boundBuffer;
  13679. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13680. var instancesBuffer = this._currentInstanceBuffers[i];
  13681. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13682. boundBuffer = instancesBuffer;
  13683. this.bindArrayBuffer(instancesBuffer);
  13684. }
  13685. var offsetLocation = this._currentInstanceLocations[i];
  13686. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13687. }
  13688. this._currentInstanceBuffers.length = 0;
  13689. this._currentInstanceLocations.length = 0;
  13690. };
  13691. /**
  13692. * Release and free the memory of a vertex array object
  13693. * @param vao defines the vertex array object to delete
  13694. */
  13695. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13696. this._gl.deleteVertexArray(vao);
  13697. };
  13698. /** @hidden */
  13699. Engine.prototype._releaseBuffer = function (buffer) {
  13700. buffer.references--;
  13701. if (buffer.references === 0) {
  13702. this._gl.deleteBuffer(buffer);
  13703. return true;
  13704. }
  13705. return false;
  13706. };
  13707. /**
  13708. * Creates a webGL buffer to use with instanciation
  13709. * @param capacity defines the size of the buffer
  13710. * @returns the webGL buffer
  13711. */
  13712. Engine.prototype.createInstancesBuffer = function (capacity) {
  13713. var buffer = this._gl.createBuffer();
  13714. if (!buffer) {
  13715. throw new Error("Unable to create instance buffer");
  13716. }
  13717. buffer.capacity = capacity;
  13718. this.bindArrayBuffer(buffer);
  13719. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13720. return buffer;
  13721. };
  13722. /**
  13723. * Delete a webGL buffer used with instanciation
  13724. * @param buffer defines the webGL buffer to delete
  13725. */
  13726. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13727. this._gl.deleteBuffer(buffer);
  13728. };
  13729. /**
  13730. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13731. * @param instancesBuffer defines the webGL buffer to update and bind
  13732. * @param data defines the data to store in the buffer
  13733. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13734. */
  13735. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13736. this.bindArrayBuffer(instancesBuffer);
  13737. if (data) {
  13738. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13739. }
  13740. if (offsetLocations[0].index !== undefined) {
  13741. var stride = 0;
  13742. for (var i = 0; i < offsetLocations.length; i++) {
  13743. var ai = offsetLocations[i];
  13744. stride += ai.attributeSize * 4;
  13745. }
  13746. for (var i = 0; i < offsetLocations.length; i++) {
  13747. var ai = offsetLocations[i];
  13748. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13749. this._gl.enableVertexAttribArray(ai.index);
  13750. this._vertexAttribArraysEnabled[ai.index] = true;
  13751. }
  13752. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13753. this._gl.vertexAttribDivisor(ai.index, 1);
  13754. this._currentInstanceLocations.push(ai.index);
  13755. this._currentInstanceBuffers.push(instancesBuffer);
  13756. }
  13757. }
  13758. else {
  13759. for (var index = 0; index < 4; index++) {
  13760. var offsetLocation = offsetLocations[index];
  13761. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13762. this._gl.enableVertexAttribArray(offsetLocation);
  13763. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13764. }
  13765. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13766. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13767. this._currentInstanceLocations.push(offsetLocation);
  13768. this._currentInstanceBuffers.push(instancesBuffer);
  13769. }
  13770. }
  13771. };
  13772. /**
  13773. * Apply all cached states (depth, culling, stencil and alpha)
  13774. */
  13775. Engine.prototype.applyStates = function () {
  13776. this._depthCullingState.apply(this._gl);
  13777. this._stencilState.apply(this._gl);
  13778. this._alphaState.apply(this._gl);
  13779. };
  13780. /**
  13781. * Send a draw order
  13782. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13783. * @param indexStart defines the starting index
  13784. * @param indexCount defines the number of index to draw
  13785. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13786. */
  13787. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13788. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13789. };
  13790. /**
  13791. * Draw a list of points
  13792. * @param verticesStart defines the index of first vertex to draw
  13793. * @param verticesCount defines the count of vertices to draw
  13794. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13795. */
  13796. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13797. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13798. };
  13799. /**
  13800. * Draw a list of unindexed primitives
  13801. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13802. * @param verticesStart defines the index of first vertex to draw
  13803. * @param verticesCount defines the count of vertices to draw
  13804. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13805. */
  13806. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13807. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13808. };
  13809. /**
  13810. * Draw a list of indexed primitives
  13811. * @param fillMode defines the primitive to use
  13812. * @param indexStart defines the starting index
  13813. * @param indexCount defines the number of index to draw
  13814. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13815. */
  13816. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13817. // Apply states
  13818. this.applyStates();
  13819. this._drawCalls.addCount(1, false);
  13820. // Render
  13821. var drawMode = this._drawMode(fillMode);
  13822. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13823. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13824. if (instancesCount) {
  13825. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13826. }
  13827. else {
  13828. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13829. }
  13830. };
  13831. /**
  13832. * Draw a list of unindexed primitives
  13833. * @param fillMode defines the primitive to use
  13834. * @param verticesStart defines the index of first vertex to draw
  13835. * @param verticesCount defines the count of vertices to draw
  13836. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13837. */
  13838. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13839. // Apply states
  13840. this.applyStates();
  13841. this._drawCalls.addCount(1, false);
  13842. var drawMode = this._drawMode(fillMode);
  13843. if (instancesCount) {
  13844. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13845. }
  13846. else {
  13847. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13848. }
  13849. };
  13850. Engine.prototype._drawMode = function (fillMode) {
  13851. switch (fillMode) {
  13852. // Triangle views
  13853. case BABYLON.Material.TriangleFillMode:
  13854. return this._gl.TRIANGLES;
  13855. case BABYLON.Material.PointFillMode:
  13856. return this._gl.POINTS;
  13857. case BABYLON.Material.WireFrameFillMode:
  13858. return this._gl.LINES;
  13859. // Draw modes
  13860. case BABYLON.Material.PointListDrawMode:
  13861. return this._gl.POINTS;
  13862. case BABYLON.Material.LineListDrawMode:
  13863. return this._gl.LINES;
  13864. case BABYLON.Material.LineLoopDrawMode:
  13865. return this._gl.LINE_LOOP;
  13866. case BABYLON.Material.LineStripDrawMode:
  13867. return this._gl.LINE_STRIP;
  13868. case BABYLON.Material.TriangleStripDrawMode:
  13869. return this._gl.TRIANGLE_STRIP;
  13870. case BABYLON.Material.TriangleFanDrawMode:
  13871. return this._gl.TRIANGLE_FAN;
  13872. default:
  13873. return this._gl.TRIANGLES;
  13874. }
  13875. };
  13876. // Shaders
  13877. /** @hidden */
  13878. Engine.prototype._releaseEffect = function (effect) {
  13879. if (this._compiledEffects[effect._key]) {
  13880. delete this._compiledEffects[effect._key];
  13881. this._deleteProgram(effect.getProgram());
  13882. }
  13883. };
  13884. /** @hidden */
  13885. Engine.prototype._deleteProgram = function (program) {
  13886. if (program) {
  13887. program.__SPECTOR_rebuildProgram = null;
  13888. if (program.transformFeedback) {
  13889. this.deleteTransformFeedback(program.transformFeedback);
  13890. program.transformFeedback = null;
  13891. }
  13892. this._gl.deleteProgram(program);
  13893. }
  13894. };
  13895. /**
  13896. * Create a new effect (used to store vertex/fragment shaders)
  13897. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13898. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13899. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13900. * @param samplers defines an array of string used to represent textures
  13901. * @param defines defines the string containing the defines to use to compile the shaders
  13902. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13903. * @param onCompiled defines a function to call when the effect creation is successful
  13904. * @param onError defines a function to call when the effect creation has failed
  13905. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13906. * @returns the new Effect
  13907. */
  13908. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13909. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13910. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13911. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13912. if (this._compiledEffects[name]) {
  13913. var compiledEffect = this._compiledEffects[name];
  13914. if (onCompiled && compiledEffect.isReady()) {
  13915. onCompiled(compiledEffect);
  13916. }
  13917. return compiledEffect;
  13918. }
  13919. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13920. effect._key = name;
  13921. this._compiledEffects[name] = effect;
  13922. return effect;
  13923. };
  13924. /**
  13925. * Create an effect to use with particle systems
  13926. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13927. * @param uniformsNames defines a list of attribute names
  13928. * @param samplers defines an array of string used to represent textures
  13929. * @param defines defines the string containing the defines to use to compile the shaders
  13930. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13931. * @param onCompiled defines a function to call when the effect creation is successful
  13932. * @param onError defines a function to call when the effect creation has failed
  13933. * @returns the new Effect
  13934. */
  13935. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13936. if (uniformsNames === void 0) { uniformsNames = []; }
  13937. if (samplers === void 0) { samplers = []; }
  13938. if (defines === void 0) { defines = ""; }
  13939. return this.createEffect({
  13940. vertex: "particles",
  13941. fragmentElement: fragmentName
  13942. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13943. };
  13944. /**
  13945. * Directly creates a webGL program
  13946. * @param vertexCode defines the vertex shader code to use
  13947. * @param fragmentCode defines the fragment shader code to use
  13948. * @param context defines the webGL context to use (if not set, the current one will be used)
  13949. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13950. * @returns the new webGL program
  13951. */
  13952. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13953. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13954. context = context || this._gl;
  13955. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13956. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13957. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13958. };
  13959. /**
  13960. * Creates a webGL program
  13961. * @param vertexCode defines the vertex shader code to use
  13962. * @param fragmentCode defines the fragment shader code to use
  13963. * @param defines defines the string containing the defines to use to compile the shaders
  13964. * @param context defines the webGL context to use (if not set, the current one will be used)
  13965. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13966. * @returns the new webGL program
  13967. */
  13968. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13969. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13970. context = context || this._gl;
  13971. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13972. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13973. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13974. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13975. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13976. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13977. return program;
  13978. };
  13979. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13980. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13981. var shaderProgram = context.createProgram();
  13982. if (!shaderProgram) {
  13983. throw new Error("Unable to create program");
  13984. }
  13985. context.attachShader(shaderProgram, vertexShader);
  13986. context.attachShader(shaderProgram, fragmentShader);
  13987. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13988. var transformFeedback = this.createTransformFeedback();
  13989. this.bindTransformFeedback(transformFeedback);
  13990. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13991. shaderProgram.transformFeedback = transformFeedback;
  13992. }
  13993. context.linkProgram(shaderProgram);
  13994. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13995. this.bindTransformFeedback(null);
  13996. }
  13997. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13998. if (!linked) {
  13999. context.validateProgram(shaderProgram);
  14000. var error = context.getProgramInfoLog(shaderProgram);
  14001. if (error) {
  14002. throw new Error(error);
  14003. }
  14004. }
  14005. context.deleteShader(vertexShader);
  14006. context.deleteShader(fragmentShader);
  14007. return shaderProgram;
  14008. };
  14009. /**
  14010. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14011. * @param shaderProgram defines the webGL program to use
  14012. * @param uniformsNames defines the list of uniform names
  14013. * @returns an array of webGL uniform locations
  14014. */
  14015. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14016. var results = new Array();
  14017. for (var index = 0; index < uniformsNames.length; index++) {
  14018. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14019. }
  14020. return results;
  14021. };
  14022. /**
  14023. * Gets the lsit of active attributes for a given webGL program
  14024. * @param shaderProgram defines the webGL program to use
  14025. * @param attributesNames defines the list of attribute names to get
  14026. * @returns an array of indices indicating the offset of each attribute
  14027. */
  14028. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14029. var results = [];
  14030. for (var index = 0; index < attributesNames.length; index++) {
  14031. try {
  14032. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14033. }
  14034. catch (e) {
  14035. results.push(-1);
  14036. }
  14037. }
  14038. return results;
  14039. };
  14040. /**
  14041. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14042. * @param effect defines the effect to activate
  14043. */
  14044. Engine.prototype.enableEffect = function (effect) {
  14045. if (!effect) {
  14046. return;
  14047. }
  14048. // Use program
  14049. this.bindSamplers(effect);
  14050. this._currentEffect = effect;
  14051. if (effect.onBind) {
  14052. effect.onBind(effect);
  14053. }
  14054. effect.onBindObservable.notifyObservers(effect);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to an array of int32
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param array defines the array of int32 to store
  14060. */
  14061. Engine.prototype.setIntArray = function (uniform, array) {
  14062. if (!uniform)
  14063. return;
  14064. this._gl.uniform1iv(uniform, array);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to an array of int32 (stored as vec2)
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param array defines the array of int32 to store
  14070. */
  14071. Engine.prototype.setIntArray2 = function (uniform, array) {
  14072. if (!uniform || array.length % 2 !== 0)
  14073. return;
  14074. this._gl.uniform2iv(uniform, array);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to an array of int32 (stored as vec3)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param array defines the array of int32 to store
  14080. */
  14081. Engine.prototype.setIntArray3 = function (uniform, array) {
  14082. if (!uniform || array.length % 3 !== 0)
  14083. return;
  14084. this._gl.uniform3iv(uniform, array);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to an array of int32 (stored as vec4)
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param array defines the array of int32 to store
  14090. */
  14091. Engine.prototype.setIntArray4 = function (uniform, array) {
  14092. if (!uniform || array.length % 4 !== 0)
  14093. return;
  14094. this._gl.uniform4iv(uniform, array);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to an array of float32
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param array defines the array of float32 to store
  14100. */
  14101. Engine.prototype.setFloatArray = function (uniform, array) {
  14102. if (!uniform)
  14103. return;
  14104. this._gl.uniform1fv(uniform, array);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to an array of float32 (stored as vec2)
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param array defines the array of float32 to store
  14110. */
  14111. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14112. if (!uniform || array.length % 2 !== 0)
  14113. return;
  14114. this._gl.uniform2fv(uniform, array);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to an array of float32 (stored as vec3)
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param array defines the array of float32 to store
  14120. */
  14121. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14122. if (!uniform || array.length % 3 !== 0)
  14123. return;
  14124. this._gl.uniform3fv(uniform, array);
  14125. };
  14126. /**
  14127. * Set the value of an uniform to an array of float32 (stored as vec4)
  14128. * @param uniform defines the webGL uniform location where to store the value
  14129. * @param array defines the array of float32 to store
  14130. */
  14131. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14132. if (!uniform || array.length % 4 !== 0)
  14133. return;
  14134. this._gl.uniform4fv(uniform, array);
  14135. };
  14136. /**
  14137. * Set the value of an uniform to an array of number
  14138. * @param uniform defines the webGL uniform location where to store the value
  14139. * @param array defines the array of number to store
  14140. */
  14141. Engine.prototype.setArray = function (uniform, array) {
  14142. if (!uniform)
  14143. return;
  14144. this._gl.uniform1fv(uniform, array);
  14145. };
  14146. /**
  14147. * Set the value of an uniform to an array of number (stored as vec2)
  14148. * @param uniform defines the webGL uniform location where to store the value
  14149. * @param array defines the array of number to store
  14150. */
  14151. Engine.prototype.setArray2 = function (uniform, array) {
  14152. if (!uniform || array.length % 2 !== 0)
  14153. return;
  14154. this._gl.uniform2fv(uniform, array);
  14155. };
  14156. /**
  14157. * Set the value of an uniform to an array of number (stored as vec3)
  14158. * @param uniform defines the webGL uniform location where to store the value
  14159. * @param array defines the array of number to store
  14160. */
  14161. Engine.prototype.setArray3 = function (uniform, array) {
  14162. if (!uniform || array.length % 3 !== 0)
  14163. return;
  14164. this._gl.uniform3fv(uniform, array);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to an array of number (stored as vec4)
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param array defines the array of number to store
  14170. */
  14171. Engine.prototype.setArray4 = function (uniform, array) {
  14172. if (!uniform || array.length % 4 !== 0)
  14173. return;
  14174. this._gl.uniform4fv(uniform, array);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to an array of float32 (stored as matrices)
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param matrices defines the array of float32 to store
  14180. */
  14181. Engine.prototype.setMatrices = function (uniform, matrices) {
  14182. if (!uniform)
  14183. return;
  14184. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14185. };
  14186. /**
  14187. * Set the value of an uniform to a matrix
  14188. * @param uniform defines the webGL uniform location where to store the value
  14189. * @param matrix defines the matrix to store
  14190. */
  14191. Engine.prototype.setMatrix = function (uniform, matrix) {
  14192. if (!uniform)
  14193. return;
  14194. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14195. };
  14196. /**
  14197. * Set the value of an uniform to a matrix (3x3)
  14198. * @param uniform defines the webGL uniform location where to store the value
  14199. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14200. */
  14201. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14202. if (!uniform)
  14203. return;
  14204. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14205. };
  14206. /**
  14207. * Set the value of an uniform to a matrix (2x2)
  14208. * @param uniform defines the webGL uniform location where to store the value
  14209. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14210. */
  14211. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14212. if (!uniform)
  14213. return;
  14214. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14215. };
  14216. /**
  14217. * Set the value of an uniform to a number (int)
  14218. * @param uniform defines the webGL uniform location where to store the value
  14219. * @param value defines the int number to store
  14220. */
  14221. Engine.prototype.setInt = function (uniform, value) {
  14222. if (!uniform)
  14223. return;
  14224. this._gl.uniform1i(uniform, value);
  14225. };
  14226. /**
  14227. * Set the value of an uniform to a number (float)
  14228. * @param uniform defines the webGL uniform location where to store the value
  14229. * @param value defines the float number to store
  14230. */
  14231. Engine.prototype.setFloat = function (uniform, value) {
  14232. if (!uniform)
  14233. return;
  14234. this._gl.uniform1f(uniform, value);
  14235. };
  14236. /**
  14237. * Set the value of an uniform to a vec2
  14238. * @param uniform defines the webGL uniform location where to store the value
  14239. * @param x defines the 1st component of the value
  14240. * @param y defines the 2nd component of the value
  14241. */
  14242. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14243. if (!uniform)
  14244. return;
  14245. this._gl.uniform2f(uniform, x, y);
  14246. };
  14247. /**
  14248. * Set the value of an uniform to a vec3
  14249. * @param uniform defines the webGL uniform location where to store the value
  14250. * @param x defines the 1st component of the value
  14251. * @param y defines the 2nd component of the value
  14252. * @param z defines the 3rd component of the value
  14253. */
  14254. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14255. if (!uniform)
  14256. return;
  14257. this._gl.uniform3f(uniform, x, y, z);
  14258. };
  14259. /**
  14260. * Set the value of an uniform to a boolean
  14261. * @param uniform defines the webGL uniform location where to store the value
  14262. * @param bool defines the boolean to store
  14263. */
  14264. Engine.prototype.setBool = function (uniform, bool) {
  14265. if (!uniform)
  14266. return;
  14267. this._gl.uniform1i(uniform, bool);
  14268. };
  14269. /**
  14270. * Set the value of an uniform to a vec4
  14271. * @param uniform defines the webGL uniform location where to store the value
  14272. * @param x defines the 1st component of the value
  14273. * @param y defines the 2nd component of the value
  14274. * @param z defines the 3rd component of the value
  14275. * @param w defines the 4th component of the value
  14276. */
  14277. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14278. if (!uniform)
  14279. return;
  14280. this._gl.uniform4f(uniform, x, y, z, w);
  14281. };
  14282. /**
  14283. * Set the value of an uniform to a Color3
  14284. * @param uniform defines the webGL uniform location where to store the value
  14285. * @param color3 defines the color to store
  14286. */
  14287. Engine.prototype.setColor3 = function (uniform, color3) {
  14288. if (!uniform)
  14289. return;
  14290. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14291. };
  14292. /**
  14293. * Set the value of an uniform to a Color3 and an alpha value
  14294. * @param uniform defines the webGL uniform location where to store the value
  14295. * @param color3 defines the color to store
  14296. * @param alpha defines the alpha component to store
  14297. */
  14298. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14299. if (!uniform)
  14300. return;
  14301. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14302. };
  14303. /**
  14304. * Sets a Color4 on a uniform variable
  14305. * @param uniform defines the uniform location
  14306. * @param color4 defines the value to be set
  14307. */
  14308. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14309. if (!uniform)
  14310. return;
  14311. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14312. };
  14313. // States
  14314. /**
  14315. * Set various states to the webGL context
  14316. * @param culling defines backface culling state
  14317. * @param zOffset defines the value to apply to zOffset (0 by default)
  14318. * @param force defines if states must be applied even if cache is up to date
  14319. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14320. */
  14321. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14322. if (zOffset === void 0) { zOffset = 0; }
  14323. if (reverseSide === void 0) { reverseSide = false; }
  14324. // Culling
  14325. if (this._depthCullingState.cull !== culling || force) {
  14326. this._depthCullingState.cull = culling;
  14327. }
  14328. // Cull face
  14329. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14330. if (this._depthCullingState.cullFace !== cullFace || force) {
  14331. this._depthCullingState.cullFace = cullFace;
  14332. }
  14333. // Z offset
  14334. this.setZOffset(zOffset);
  14335. // Front face
  14336. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14337. if (this._depthCullingState.frontFace !== frontFace || force) {
  14338. this._depthCullingState.frontFace = frontFace;
  14339. }
  14340. };
  14341. /**
  14342. * Set the z offset to apply to current rendering
  14343. * @param value defines the offset to apply
  14344. */
  14345. Engine.prototype.setZOffset = function (value) {
  14346. this._depthCullingState.zOffset = value;
  14347. };
  14348. /**
  14349. * Gets the current value of the zOffset
  14350. * @returns the current zOffset state
  14351. */
  14352. Engine.prototype.getZOffset = function () {
  14353. return this._depthCullingState.zOffset;
  14354. };
  14355. /**
  14356. * Enable or disable depth buffering
  14357. * @param enable defines the state to set
  14358. */
  14359. Engine.prototype.setDepthBuffer = function (enable) {
  14360. this._depthCullingState.depthTest = enable;
  14361. };
  14362. /**
  14363. * Gets a boolean indicating if depth writing is enabled
  14364. * @returns the current depth writing state
  14365. */
  14366. Engine.prototype.getDepthWrite = function () {
  14367. return this._depthCullingState.depthMask;
  14368. };
  14369. /**
  14370. * Enable or disable depth writing
  14371. * @param enable defines the state to set
  14372. */
  14373. Engine.prototype.setDepthWrite = function (enable) {
  14374. this._depthCullingState.depthMask = enable;
  14375. };
  14376. /**
  14377. * Enable or disable color writing
  14378. * @param enable defines the state to set
  14379. */
  14380. Engine.prototype.setColorWrite = function (enable) {
  14381. this._gl.colorMask(enable, enable, enable, enable);
  14382. this._colorWrite = enable;
  14383. };
  14384. /**
  14385. * Gets a boolean indicating if color writing is enabled
  14386. * @returns the current color writing state
  14387. */
  14388. Engine.prototype.getColorWrite = function () {
  14389. return this._colorWrite;
  14390. };
  14391. /**
  14392. * Sets alpha constants used by some alpha blending modes
  14393. * @param r defines the red component
  14394. * @param g defines the green component
  14395. * @param b defines the blue component
  14396. * @param a defines the alpha component
  14397. */
  14398. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14399. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14400. };
  14401. /**
  14402. * Sets the current alpha mode
  14403. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14404. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14405. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14406. */
  14407. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14408. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14409. if (this._alphaMode === mode) {
  14410. return;
  14411. }
  14412. switch (mode) {
  14413. case Engine.ALPHA_DISABLE:
  14414. this._alphaState.alphaBlend = false;
  14415. break;
  14416. case Engine.ALPHA_PREMULTIPLIED:
  14417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14418. this._alphaState.alphaBlend = true;
  14419. break;
  14420. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14422. this._alphaState.alphaBlend = true;
  14423. break;
  14424. case Engine.ALPHA_COMBINE:
  14425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14426. this._alphaState.alphaBlend = true;
  14427. break;
  14428. case Engine.ALPHA_ONEONE:
  14429. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14430. this._alphaState.alphaBlend = true;
  14431. break;
  14432. case Engine.ALPHA_ADD:
  14433. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14434. this._alphaState.alphaBlend = true;
  14435. break;
  14436. case Engine.ALPHA_SUBTRACT:
  14437. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14438. this._alphaState.alphaBlend = true;
  14439. break;
  14440. case Engine.ALPHA_MULTIPLY:
  14441. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14442. this._alphaState.alphaBlend = true;
  14443. break;
  14444. case Engine.ALPHA_MAXIMIZED:
  14445. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14446. this._alphaState.alphaBlend = true;
  14447. break;
  14448. case Engine.ALPHA_INTERPOLATE:
  14449. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14450. this._alphaState.alphaBlend = true;
  14451. break;
  14452. case Engine.ALPHA_SCREENMODE:
  14453. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14454. this._alphaState.alphaBlend = true;
  14455. break;
  14456. }
  14457. if (!noDepthWriteChange) {
  14458. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14459. }
  14460. this._alphaMode = mode;
  14461. };
  14462. /**
  14463. * Gets the current alpha mode
  14464. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14465. * @returns the current alpha mode
  14466. */
  14467. Engine.prototype.getAlphaMode = function () {
  14468. return this._alphaMode;
  14469. };
  14470. // Textures
  14471. /**
  14472. * Force the entire cache to be cleared
  14473. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14474. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14475. */
  14476. Engine.prototype.wipeCaches = function (bruteForce) {
  14477. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14478. return;
  14479. }
  14480. this._currentEffect = null;
  14481. if (bruteForce) {
  14482. this.resetTextureCache();
  14483. this._currentProgram = null;
  14484. this._stencilState.reset();
  14485. this._depthCullingState.reset();
  14486. this.setDepthFunctionToLessOrEqual();
  14487. this._alphaState.reset();
  14488. }
  14489. this._resetVertexBufferBinding();
  14490. this._cachedIndexBuffer = null;
  14491. this._cachedEffectForVertexBuffers = null;
  14492. this._unbindVertexArrayObject();
  14493. this.bindIndexBuffer(null);
  14494. };
  14495. /**
  14496. * Set the compressed texture format to use, based on the formats you have, and the formats
  14497. * supported by the hardware / browser.
  14498. *
  14499. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14500. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14501. * to API arguments needed to compressed textures. This puts the burden on the container
  14502. * generator to house the arcane code for determining these for current & future formats.
  14503. *
  14504. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14505. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14506. *
  14507. * Note: The result of this call is not taken into account when a texture is base64.
  14508. *
  14509. * @param formatsAvailable defines the list of those format families you have created
  14510. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14511. *
  14512. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14513. * @returns The extension selected.
  14514. */
  14515. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14516. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14517. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14518. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14519. return this._textureFormatInUse = this._texturesSupported[i];
  14520. }
  14521. }
  14522. }
  14523. // actively set format to nothing, to allow this to be called more than once
  14524. // and possibly fail the 2nd time
  14525. this._textureFormatInUse = null;
  14526. return null;
  14527. };
  14528. /** @hidden */
  14529. Engine.prototype._createTexture = function () {
  14530. var texture = this._gl.createTexture();
  14531. if (!texture) {
  14532. throw new Error("Unable to create texture");
  14533. }
  14534. return texture;
  14535. };
  14536. /**
  14537. * Usually called from BABYLON.Texture.ts.
  14538. * Passed information to create a WebGLTexture
  14539. * @param urlArg defines a value which contains one of the following:
  14540. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14541. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14542. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14543. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14544. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14545. * @param scene needed for loading to the correct scene
  14546. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14547. * @param onLoad optional callback to be called upon successful completion
  14548. * @param onError optional callback to be called upon failure
  14549. * @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
  14550. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14551. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14552. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14553. */
  14554. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14555. var _this = this;
  14556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14557. if (onLoad === void 0) { onLoad = null; }
  14558. if (onError === void 0) { onError = null; }
  14559. if (buffer === void 0) { buffer = null; }
  14560. if (fallback === void 0) { fallback = null; }
  14561. if (format === void 0) { format = null; }
  14562. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14563. var fromData = url.substr(0, 5) === "data:";
  14564. var fromBlob = url.substr(0, 5) === "blob:";
  14565. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14566. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14567. // establish the file extension, if possible
  14568. var lastDot = url.lastIndexOf('.');
  14569. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14570. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14571. var isTGA = (extension.indexOf(".tga") === 0);
  14572. // determine if a ktx file should be substituted
  14573. var isKTX = false;
  14574. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14575. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14576. isKTX = true;
  14577. }
  14578. if (scene) {
  14579. scene._addPendingData(texture);
  14580. }
  14581. texture.url = url;
  14582. texture.generateMipMaps = !noMipmap;
  14583. texture.samplingMode = samplingMode;
  14584. texture.invertY = invertY;
  14585. if (!this._doNotHandleContextLost) {
  14586. // Keep a link to the buffer only if we plan to handle context lost
  14587. texture._buffer = buffer;
  14588. }
  14589. var onLoadObserver = null;
  14590. if (onLoad && !fallback) {
  14591. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14592. }
  14593. if (!fallback)
  14594. this._internalTexturesCache.push(texture);
  14595. var onerror = function (message, exception) {
  14596. if (scene) {
  14597. scene._removePendingData(texture);
  14598. }
  14599. if (onLoadObserver) {
  14600. texture.onLoadedObservable.remove(onLoadObserver);
  14601. }
  14602. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14603. if (isKTX) {
  14604. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14605. }
  14606. else if (BABYLON.Tools.UseFallbackTexture) {
  14607. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14608. }
  14609. if (onError) {
  14610. onError(message || "Unknown error", exception);
  14611. }
  14612. };
  14613. var callback = null;
  14614. // processing for non-image formats
  14615. if (isKTX || isTGA || isDDS) {
  14616. if (isKTX) {
  14617. callback = function (data) {
  14618. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14619. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14620. ktx.uploadLevels(_this._gl, !noMipmap);
  14621. return false;
  14622. }, samplingMode);
  14623. };
  14624. }
  14625. else if (isTGA) {
  14626. callback = function (arrayBuffer) {
  14627. var data = new Uint8Array(arrayBuffer);
  14628. var header = BABYLON.TGATools.GetTGAHeader(data);
  14629. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14630. BABYLON.TGATools.UploadContent(_this._gl, data);
  14631. return false;
  14632. }, samplingMode);
  14633. };
  14634. }
  14635. else if (isDDS) {
  14636. callback = function (data) {
  14637. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14638. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14639. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14640. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14641. return false;
  14642. }, samplingMode);
  14643. };
  14644. }
  14645. if (!buffer) {
  14646. this._loadFile(url, function (data) {
  14647. if (callback) {
  14648. callback(data);
  14649. }
  14650. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14651. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14652. });
  14653. }
  14654. else {
  14655. if (callback) {
  14656. callback(buffer);
  14657. }
  14658. }
  14659. // image format processing
  14660. }
  14661. else {
  14662. var onload = function (img) {
  14663. if (fromBlob && !_this._doNotHandleContextLost) {
  14664. // We need to store the image if we need to rebuild the texture
  14665. // in case of a webgl context lost
  14666. texture._buffer = img;
  14667. }
  14668. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14669. var gl = _this._gl;
  14670. var isPot = (img.width === potWidth && img.height === potHeight);
  14671. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14672. if (isPot) {
  14673. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14674. return false;
  14675. }
  14676. // Using shaders to rescale because canvas.drawImage is lossy
  14677. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14678. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14679. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14680. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14683. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14684. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14685. _this._releaseTexture(source);
  14686. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14687. continuationCallback();
  14688. });
  14689. return true;
  14690. }, samplingMode);
  14691. };
  14692. if (!fromData || isBase64) {
  14693. if (buffer instanceof HTMLImageElement) {
  14694. onload(buffer);
  14695. }
  14696. else {
  14697. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14698. }
  14699. }
  14700. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14701. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14702. }
  14703. else {
  14704. onload(buffer);
  14705. }
  14706. }
  14707. return texture;
  14708. };
  14709. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14710. var _this = this;
  14711. var rtt = this.createRenderTargetTexture({
  14712. width: destination.width,
  14713. height: destination.height,
  14714. }, {
  14715. generateMipMaps: false,
  14716. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14717. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14718. generateDepthBuffer: false,
  14719. generateStencilBuffer: false
  14720. });
  14721. if (!this._rescalePostProcess) {
  14722. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14723. }
  14724. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14725. _this._rescalePostProcess.onApply = function (effect) {
  14726. effect._bindTexture("textureSampler", source);
  14727. };
  14728. var hostingScene = scene;
  14729. if (!hostingScene) {
  14730. hostingScene = _this.scenes[_this.scenes.length - 1];
  14731. }
  14732. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14733. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14734. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14735. _this.unBindFramebuffer(rtt);
  14736. _this._releaseTexture(rtt);
  14737. if (onComplete) {
  14738. onComplete();
  14739. }
  14740. });
  14741. };
  14742. /**
  14743. * Update a raw texture
  14744. * @param texture defines the texture to update
  14745. * @param data defines the data to store in the texture
  14746. * @param format defines the format of the data
  14747. * @param invertY defines if data must be stored with Y axis inverted
  14748. * @param compression defines the compression used (null by default)
  14749. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14750. */
  14751. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14752. if (compression === void 0) { compression = null; }
  14753. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14754. if (!texture) {
  14755. return;
  14756. }
  14757. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14758. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14759. // babylon's internalFormat but gl's texImage2D format
  14760. var internalFormat = this._getInternalFormat(format);
  14761. var textureType = this._getWebGLTextureType(type);
  14762. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14763. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14764. if (!this._doNotHandleContextLost) {
  14765. texture._bufferView = data;
  14766. texture.format = format;
  14767. texture.type = type;
  14768. texture.invertY = invertY;
  14769. texture._compression = compression;
  14770. }
  14771. if (texture.width % 4 !== 0) {
  14772. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14773. }
  14774. if (compression && data) {
  14775. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14776. }
  14777. else {
  14778. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14779. }
  14780. if (texture.generateMipMaps) {
  14781. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14782. }
  14783. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14784. // this.resetTextureCache();
  14785. texture.isReady = true;
  14786. };
  14787. /**
  14788. * Creates a raw texture
  14789. * @param data defines the data to store in the texture
  14790. * @param width defines the width of the texture
  14791. * @param height defines the height of the texture
  14792. * @param format defines the format of the data
  14793. * @param generateMipMaps defines if the engine should generate the mip levels
  14794. * @param invertY defines if data must be stored with Y axis inverted
  14795. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14796. * @param compression defines the compression used (null by default)
  14797. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14798. * @returns the raw texture inside an InternalTexture
  14799. */
  14800. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14801. if (compression === void 0) { compression = null; }
  14802. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14803. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14804. texture.baseWidth = width;
  14805. texture.baseHeight = height;
  14806. texture.width = width;
  14807. texture.height = height;
  14808. texture.format = format;
  14809. texture.generateMipMaps = generateMipMaps;
  14810. texture.samplingMode = samplingMode;
  14811. texture.invertY = invertY;
  14812. texture._compression = compression;
  14813. texture.type = type;
  14814. if (!this._doNotHandleContextLost) {
  14815. texture._bufferView = data;
  14816. }
  14817. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14818. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14819. // Filters
  14820. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14821. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14822. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14823. if (generateMipMaps) {
  14824. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14825. }
  14826. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14827. this._internalTexturesCache.push(texture);
  14828. return texture;
  14829. };
  14830. /**
  14831. * Creates a dynamic texture
  14832. * @param width defines the width of the texture
  14833. * @param height defines the height of the texture
  14834. * @param generateMipMaps defines if the engine should generate the mip levels
  14835. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14836. * @returns the dynamic texture inside an InternalTexture
  14837. */
  14838. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14839. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14840. texture.baseWidth = width;
  14841. texture.baseHeight = height;
  14842. if (generateMipMaps) {
  14843. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14844. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14845. }
  14846. // this.resetTextureCache();
  14847. texture.width = width;
  14848. texture.height = height;
  14849. texture.isReady = false;
  14850. texture.generateMipMaps = generateMipMaps;
  14851. texture.samplingMode = samplingMode;
  14852. this.updateTextureSamplingMode(samplingMode, texture);
  14853. this._internalTexturesCache.push(texture);
  14854. return texture;
  14855. };
  14856. /**
  14857. * Update the sampling mode of a given texture
  14858. * @param samplingMode defines the required sampling mode
  14859. * @param texture defines the texture to update
  14860. */
  14861. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14862. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14863. if (texture.isCube) {
  14864. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14865. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14866. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14867. }
  14868. else if (texture.is3D) {
  14869. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14870. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14871. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14872. }
  14873. else {
  14874. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14875. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14876. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14877. }
  14878. texture.samplingMode = samplingMode;
  14879. };
  14880. /**
  14881. * Update the content of a dynamic texture
  14882. * @param texture defines the texture to update
  14883. * @param canvas defines the canvas containing the source
  14884. * @param invertY defines if data must be stored with Y axis inverted
  14885. * @param premulAlpha defines if alpha is stored as premultiplied
  14886. * @param format defines the format of the data
  14887. */
  14888. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14889. if (premulAlpha === void 0) { premulAlpha = false; }
  14890. if (!texture) {
  14891. return;
  14892. }
  14893. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14894. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14895. if (premulAlpha) {
  14896. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14897. }
  14898. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14899. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14900. if (texture.generateMipMaps) {
  14901. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14902. }
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14904. if (premulAlpha) {
  14905. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14906. }
  14907. texture.isReady = true;
  14908. };
  14909. /**
  14910. * Update a video texture
  14911. * @param texture defines the texture to update
  14912. * @param video defines the video element to use
  14913. * @param invertY defines if data must be stored with Y axis inverted
  14914. */
  14915. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14916. if (!texture || texture._isDisabled) {
  14917. return;
  14918. }
  14919. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14920. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14921. try {
  14922. // Testing video texture support
  14923. if (this._videoTextureSupported === undefined) {
  14924. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14925. if (this._gl.getError() !== 0) {
  14926. this._videoTextureSupported = false;
  14927. }
  14928. else {
  14929. this._videoTextureSupported = true;
  14930. }
  14931. }
  14932. // Copy video through the current working canvas if video texture is not supported
  14933. if (!this._videoTextureSupported) {
  14934. if (!texture._workingCanvas) {
  14935. texture._workingCanvas = document.createElement("canvas");
  14936. var context = texture._workingCanvas.getContext("2d");
  14937. if (!context) {
  14938. throw new Error("Unable to get 2d context");
  14939. }
  14940. texture._workingContext = context;
  14941. texture._workingCanvas.width = texture.width;
  14942. texture._workingCanvas.height = texture.height;
  14943. }
  14944. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14945. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14946. }
  14947. else {
  14948. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14949. }
  14950. if (texture.generateMipMaps) {
  14951. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14952. }
  14953. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14954. // this.resetTextureCache();
  14955. texture.isReady = true;
  14956. }
  14957. catch (ex) {
  14958. // Something unexpected
  14959. // Let's disable the texture
  14960. texture._isDisabled = true;
  14961. }
  14962. };
  14963. /**
  14964. * Updates a depth texture Comparison Mode and Function.
  14965. * If the comparison Function is equal to 0, the mode will be set to none.
  14966. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14967. * @param texture The texture to set the comparison function for
  14968. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14969. */
  14970. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14971. if (this.webGLVersion === 1) {
  14972. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14973. return;
  14974. }
  14975. var gl = this._gl;
  14976. if (texture.isCube) {
  14977. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14978. if (comparisonFunction === 0) {
  14979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14981. }
  14982. else {
  14983. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14984. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14985. }
  14986. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14987. }
  14988. else {
  14989. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14990. if (comparisonFunction === 0) {
  14991. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14992. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14993. }
  14994. else {
  14995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14997. }
  14998. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14999. }
  15000. texture._comparisonFunction = comparisonFunction;
  15001. };
  15002. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15003. var width = size.width || size;
  15004. var height = size.height || size;
  15005. internalTexture.baseWidth = width;
  15006. internalTexture.baseHeight = height;
  15007. internalTexture.width = width;
  15008. internalTexture.height = height;
  15009. internalTexture.isReady = true;
  15010. internalTexture.samples = 1;
  15011. internalTexture.generateMipMaps = false;
  15012. internalTexture._generateDepthBuffer = true;
  15013. internalTexture._generateStencilBuffer = generateStencil;
  15014. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15015. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15016. internalTexture._comparisonFunction = comparisonFunction;
  15017. var gl = this._gl;
  15018. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15019. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15020. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15021. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15022. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15023. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15024. if (comparisonFunction === 0) {
  15025. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15026. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15027. }
  15028. else {
  15029. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15030. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15031. }
  15032. };
  15033. /**
  15034. * Creates a depth stencil texture.
  15035. * This is only available in WebGL 2 or with the depth texture extension available.
  15036. * @param size The size of face edge in the texture.
  15037. * @param options The options defining the texture.
  15038. * @returns The texture
  15039. */
  15040. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15041. if (options.isCube) {
  15042. var width = size.width || size;
  15043. return this._createDepthStencilCubeTexture(width, options);
  15044. }
  15045. else {
  15046. return this._createDepthStencilTexture(size, options);
  15047. }
  15048. };
  15049. /**
  15050. * Creates a depth stencil texture.
  15051. * This is only available in WebGL 2 or with the depth texture extension available.
  15052. * @param size The size of face edge in the texture.
  15053. * @param options The options defining the texture.
  15054. * @returns The texture
  15055. */
  15056. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15057. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15058. if (!this._caps.depthTextureExtension) {
  15059. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15060. return internalTexture;
  15061. }
  15062. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15063. var gl = this._gl;
  15064. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15065. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15066. if (this.webGLVersion > 1) {
  15067. if (internalOptions.generateStencil) {
  15068. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15069. }
  15070. else {
  15071. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15072. }
  15073. }
  15074. else {
  15075. if (internalOptions.generateStencil) {
  15076. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15077. }
  15078. else {
  15079. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15080. }
  15081. }
  15082. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15083. return internalTexture;
  15084. };
  15085. /**
  15086. * Creates a depth stencil cube texture.
  15087. * This is only available in WebGL 2.
  15088. * @param size The size of face edge in the cube texture.
  15089. * @param options The options defining the cube texture.
  15090. * @returns The cube texture
  15091. */
  15092. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15093. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15094. internalTexture.isCube = true;
  15095. if (this.webGLVersion === 1) {
  15096. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15097. return internalTexture;
  15098. }
  15099. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15100. var gl = this._gl;
  15101. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15102. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15103. // Create the depth/stencil buffer
  15104. for (var face = 0; face < 6; face++) {
  15105. if (internalOptions.generateStencil) {
  15106. 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);
  15107. }
  15108. else {
  15109. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15110. }
  15111. }
  15112. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15113. return internalTexture;
  15114. };
  15115. /**
  15116. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15117. * @param renderTarget The render target to set the frame buffer for
  15118. */
  15119. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15120. // Create the framebuffer
  15121. var internalTexture = renderTarget.getInternalTexture();
  15122. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15123. return;
  15124. }
  15125. var gl = this._gl;
  15126. var depthStencilTexture = renderTarget.depthStencilTexture;
  15127. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15128. if (depthStencilTexture.isCube) {
  15129. if (depthStencilTexture._generateStencilBuffer) {
  15130. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15131. }
  15132. else {
  15133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15134. }
  15135. }
  15136. else {
  15137. if (depthStencilTexture._generateStencilBuffer) {
  15138. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15139. }
  15140. else {
  15141. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15142. }
  15143. }
  15144. this.bindUnboundFramebuffer(null);
  15145. };
  15146. /**
  15147. * Creates a new render target texture
  15148. * @param size defines the size of the texture
  15149. * @param options defines the options used to create the texture
  15150. * @returns a new render target texture stored in an InternalTexture
  15151. */
  15152. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15153. var fullOptions = new RenderTargetCreationOptions();
  15154. if (options !== undefined && typeof options === "object") {
  15155. fullOptions.generateMipMaps = options.generateMipMaps;
  15156. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15157. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15158. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15159. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15160. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15161. }
  15162. else {
  15163. fullOptions.generateMipMaps = options;
  15164. fullOptions.generateDepthBuffer = true;
  15165. fullOptions.generateStencilBuffer = false;
  15166. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15167. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15168. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15169. }
  15170. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15171. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15172. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15173. }
  15174. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15175. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15176. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15177. }
  15178. var gl = this._gl;
  15179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15180. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15181. var width = size.width || size;
  15182. var height = size.height || size;
  15183. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15184. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15185. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15186. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15187. }
  15188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15192. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15193. // Create the framebuffer
  15194. var currentFrameBuffer = this._currentFramebuffer;
  15195. var framebuffer = gl.createFramebuffer();
  15196. this.bindUnboundFramebuffer(framebuffer);
  15197. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15198. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15199. if (fullOptions.generateMipMaps) {
  15200. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15201. }
  15202. // Unbind
  15203. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15204. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15205. this.bindUnboundFramebuffer(currentFrameBuffer);
  15206. texture._framebuffer = framebuffer;
  15207. texture.baseWidth = width;
  15208. texture.baseHeight = height;
  15209. texture.width = width;
  15210. texture.height = height;
  15211. texture.isReady = true;
  15212. texture.samples = 1;
  15213. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15214. texture.samplingMode = fullOptions.samplingMode;
  15215. texture.type = fullOptions.type;
  15216. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15217. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15218. // this.resetTextureCache();
  15219. this._internalTexturesCache.push(texture);
  15220. return texture;
  15221. };
  15222. /**
  15223. * Create a multi render target texture
  15224. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15225. * @param size defines the size of the texture
  15226. * @param options defines the creation options
  15227. * @returns the cube texture as an InternalTexture
  15228. */
  15229. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15230. var generateMipMaps = false;
  15231. var generateDepthBuffer = true;
  15232. var generateStencilBuffer = false;
  15233. var generateDepthTexture = false;
  15234. var textureCount = 1;
  15235. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15236. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15237. var types = new Array();
  15238. var samplingModes = new Array();
  15239. if (options !== undefined) {
  15240. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15241. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15242. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15243. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15244. textureCount = options.textureCount || 1;
  15245. if (options.types) {
  15246. types = options.types;
  15247. }
  15248. if (options.samplingModes) {
  15249. samplingModes = options.samplingModes;
  15250. }
  15251. }
  15252. var gl = this._gl;
  15253. // Create the framebuffer
  15254. var framebuffer = gl.createFramebuffer();
  15255. this.bindUnboundFramebuffer(framebuffer);
  15256. var width = size.width || size;
  15257. var height = size.height || size;
  15258. var textures = [];
  15259. var attachments = [];
  15260. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15261. for (var i = 0; i < textureCount; i++) {
  15262. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15263. var type = types[i] || defaultType;
  15264. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15265. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15266. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15267. }
  15268. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15269. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15270. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15271. }
  15272. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15273. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15274. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15275. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15276. }
  15277. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15278. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15279. textures.push(texture);
  15280. attachments.push(attachment);
  15281. gl.activeTexture(gl["TEXTURE" + i]);
  15282. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15287. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15288. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15289. if (generateMipMaps) {
  15290. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15291. }
  15292. // Unbind
  15293. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15294. texture._framebuffer = framebuffer;
  15295. texture._depthStencilBuffer = depthStencilBuffer;
  15296. texture.baseWidth = width;
  15297. texture.baseHeight = height;
  15298. texture.width = width;
  15299. texture.height = height;
  15300. texture.isReady = true;
  15301. texture.samples = 1;
  15302. texture.generateMipMaps = generateMipMaps;
  15303. texture.samplingMode = samplingMode;
  15304. texture.type = type;
  15305. texture._generateDepthBuffer = generateDepthBuffer;
  15306. texture._generateStencilBuffer = generateStencilBuffer;
  15307. texture._attachments = attachments;
  15308. this._internalTexturesCache.push(texture);
  15309. }
  15310. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15311. // Depth texture
  15312. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15313. gl.activeTexture(gl.TEXTURE0);
  15314. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15315. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15316. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15317. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15319. 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);
  15320. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15321. depthTexture._framebuffer = framebuffer;
  15322. depthTexture.baseWidth = width;
  15323. depthTexture.baseHeight = height;
  15324. depthTexture.width = width;
  15325. depthTexture.height = height;
  15326. depthTexture.isReady = true;
  15327. depthTexture.samples = 1;
  15328. depthTexture.generateMipMaps = generateMipMaps;
  15329. depthTexture.samplingMode = gl.NEAREST;
  15330. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15331. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15332. textures.push(depthTexture);
  15333. this._internalTexturesCache.push(depthTexture);
  15334. }
  15335. gl.drawBuffers(attachments);
  15336. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15337. this.bindUnboundFramebuffer(null);
  15338. this.resetTextureCache();
  15339. return textures;
  15340. };
  15341. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15342. if (samples === void 0) { samples = 1; }
  15343. var depthStencilBuffer = null;
  15344. var gl = this._gl;
  15345. // Create the depth/stencil buffer
  15346. if (generateStencilBuffer) {
  15347. depthStencilBuffer = gl.createRenderbuffer();
  15348. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15349. if (samples > 1) {
  15350. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15351. }
  15352. else {
  15353. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15354. }
  15355. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15356. }
  15357. else if (generateDepthBuffer) {
  15358. depthStencilBuffer = gl.createRenderbuffer();
  15359. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15360. if (samples > 1) {
  15361. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15362. }
  15363. else {
  15364. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15365. }
  15366. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15367. }
  15368. return depthStencilBuffer;
  15369. };
  15370. /**
  15371. * Updates the sample count of a render target texture
  15372. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15373. * @param texture defines the texture to update
  15374. * @param samples defines the sample count to set
  15375. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15376. */
  15377. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15378. if (this.webGLVersion < 2 || !texture) {
  15379. return 1;
  15380. }
  15381. if (texture.samples === samples) {
  15382. return samples;
  15383. }
  15384. var gl = this._gl;
  15385. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15386. // Dispose previous render buffers
  15387. if (texture._depthStencilBuffer) {
  15388. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15389. texture._depthStencilBuffer = null;
  15390. }
  15391. if (texture._MSAAFramebuffer) {
  15392. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15393. texture._MSAAFramebuffer = null;
  15394. }
  15395. if (texture._MSAARenderBuffer) {
  15396. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15397. texture._MSAARenderBuffer = null;
  15398. }
  15399. if (samples > 1) {
  15400. var framebuffer = gl.createFramebuffer();
  15401. if (!framebuffer) {
  15402. throw new Error("Unable to create multi sampled framebuffer");
  15403. }
  15404. texture._MSAAFramebuffer = framebuffer;
  15405. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15406. var colorRenderbuffer = gl.createRenderbuffer();
  15407. if (!colorRenderbuffer) {
  15408. throw new Error("Unable to create multi sampled framebuffer");
  15409. }
  15410. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15411. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15412. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15413. texture._MSAARenderBuffer = colorRenderbuffer;
  15414. }
  15415. else {
  15416. this.bindUnboundFramebuffer(texture._framebuffer);
  15417. }
  15418. texture.samples = samples;
  15419. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15420. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15421. this.bindUnboundFramebuffer(null);
  15422. return samples;
  15423. };
  15424. /**
  15425. * Update the sample count for a given multiple render target texture
  15426. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15427. * @param textures defines the textures to update
  15428. * @param samples defines the sample count to set
  15429. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15430. */
  15431. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15432. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15433. return 1;
  15434. }
  15435. if (textures[0].samples === samples) {
  15436. return samples;
  15437. }
  15438. var gl = this._gl;
  15439. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15440. // Dispose previous render buffers
  15441. if (textures[0]._depthStencilBuffer) {
  15442. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15443. textures[0]._depthStencilBuffer = null;
  15444. }
  15445. if (textures[0]._MSAAFramebuffer) {
  15446. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15447. textures[0]._MSAAFramebuffer = null;
  15448. }
  15449. for (var i = 0; i < textures.length; i++) {
  15450. if (textures[i]._MSAARenderBuffer) {
  15451. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15452. textures[i]._MSAARenderBuffer = null;
  15453. }
  15454. }
  15455. if (samples > 1) {
  15456. var framebuffer = gl.createFramebuffer();
  15457. if (!framebuffer) {
  15458. throw new Error("Unable to create multi sampled framebuffer");
  15459. }
  15460. this.bindUnboundFramebuffer(framebuffer);
  15461. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15462. var attachments = [];
  15463. for (var i = 0; i < textures.length; i++) {
  15464. var texture = textures[i];
  15465. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15466. var colorRenderbuffer = gl.createRenderbuffer();
  15467. if (!colorRenderbuffer) {
  15468. throw new Error("Unable to create multi sampled framebuffer");
  15469. }
  15470. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15471. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15472. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15473. texture._MSAAFramebuffer = framebuffer;
  15474. texture._MSAARenderBuffer = colorRenderbuffer;
  15475. texture.samples = samples;
  15476. texture._depthStencilBuffer = depthStencilBuffer;
  15477. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15478. attachments.push(attachment);
  15479. }
  15480. gl.drawBuffers(attachments);
  15481. }
  15482. else {
  15483. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15484. }
  15485. this.bindUnboundFramebuffer(null);
  15486. return samples;
  15487. };
  15488. /** @hidden */
  15489. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15490. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15491. };
  15492. /** @hidden */
  15493. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15494. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15495. };
  15496. /**
  15497. * Creates a new render target cube texture
  15498. * @param size defines the size of the texture
  15499. * @param options defines the options used to create the texture
  15500. * @returns a new render target cube texture stored in an InternalTexture
  15501. */
  15502. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15503. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15504. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15505. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15506. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15507. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15508. }
  15509. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15510. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15511. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15512. }
  15513. var gl = this._gl;
  15514. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15515. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15516. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15517. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15518. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15519. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15520. }
  15521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15524. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15525. for (var face = 0; face < 6; face++) {
  15526. 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);
  15527. }
  15528. // Create the framebuffer
  15529. var framebuffer = gl.createFramebuffer();
  15530. this.bindUnboundFramebuffer(framebuffer);
  15531. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15532. // MipMaps
  15533. if (fullOptions.generateMipMaps) {
  15534. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15535. }
  15536. // Unbind
  15537. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15538. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15539. this.bindUnboundFramebuffer(null);
  15540. texture._framebuffer = framebuffer;
  15541. texture.width = size;
  15542. texture.height = size;
  15543. texture.isReady = true;
  15544. texture.isCube = true;
  15545. texture.samples = 1;
  15546. texture.generateMipMaps = fullOptions.generateMipMaps;
  15547. texture.samplingMode = fullOptions.samplingMode;
  15548. texture.type = fullOptions.type;
  15549. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15550. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15551. this._internalTexturesCache.push(texture);
  15552. return texture;
  15553. };
  15554. /**
  15555. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15556. * @param rootUrl defines the url where the file to load is located
  15557. * @param scene defines the current scene
  15558. * @param scale defines scale to apply to the mip map selection
  15559. * @param offset defines offset to apply to the mip map selection
  15560. * @param onLoad defines an optional callback raised when the texture is loaded
  15561. * @param onError defines an optional callback raised if there is an issue to load the texture
  15562. * @param format defines the format of the data
  15563. * @param forcedExtension defines the extension to use to pick the right loader
  15564. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15565. * @returns the cube texture as an InternalTexture
  15566. */
  15567. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15568. var _this = this;
  15569. if (onLoad === void 0) { onLoad = null; }
  15570. if (onError === void 0) { onError = null; }
  15571. if (forcedExtension === void 0) { forcedExtension = null; }
  15572. if (createPolynomials === void 0) { createPolynomials = true; }
  15573. var callback = function (loadData) {
  15574. if (!loadData) {
  15575. if (onLoad) {
  15576. onLoad(null);
  15577. }
  15578. return;
  15579. }
  15580. var texture = loadData.texture;
  15581. if (!createPolynomials) {
  15582. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15583. }
  15584. else if (loadData.info.sphericalPolynomial) {
  15585. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15586. }
  15587. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15588. texture._lodGenerationScale = scale;
  15589. texture._lodGenerationOffset = offset;
  15590. if (_this._caps.textureLOD) {
  15591. // Do not add extra process if texture lod is supported.
  15592. if (onLoad) {
  15593. onLoad(texture);
  15594. }
  15595. return;
  15596. }
  15597. var mipSlices = 3;
  15598. var gl = _this._gl;
  15599. var width = loadData.width;
  15600. if (!width) {
  15601. return;
  15602. }
  15603. var textures = [];
  15604. for (var i = 0; i < mipSlices; i++) {
  15605. //compute LOD from even spacing in smoothness (matching shader calculation)
  15606. var smoothness = i / (mipSlices - 1);
  15607. var roughness = 1 - smoothness;
  15608. var minLODIndex = offset; // roughness = 0
  15609. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15610. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15611. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15612. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15613. glTextureFromLod.isCube = true;
  15614. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15616. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15619. if (loadData.isDDS) {
  15620. var info = loadData.info;
  15621. var data = loadData.data;
  15622. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15623. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15624. }
  15625. else {
  15626. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15627. }
  15628. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15629. // Wrap in a base texture for easy binding.
  15630. var lodTexture = new BABYLON.BaseTexture(scene);
  15631. lodTexture.isCube = true;
  15632. lodTexture._texture = glTextureFromLod;
  15633. glTextureFromLod.isReady = true;
  15634. textures.push(lodTexture);
  15635. }
  15636. texture._lodTextureHigh = textures[2];
  15637. texture._lodTextureMid = textures[1];
  15638. texture._lodTextureLow = textures[0];
  15639. if (onLoad) {
  15640. onLoad(texture);
  15641. }
  15642. };
  15643. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15644. };
  15645. /**
  15646. * Creates a cube texture
  15647. * @param rootUrl defines the url where the files to load is located
  15648. * @param scene defines the current scene
  15649. * @param files defines the list of files to load (1 per face)
  15650. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15651. * @param onLoad defines an optional callback raised when the texture is loaded
  15652. * @param onError defines an optional callback raised if there is an issue to load the texture
  15653. * @param format defines the format of the data
  15654. * @param forcedExtension defines the extension to use to pick the right loader
  15655. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15656. * @returns the cube texture as an InternalTexture
  15657. */
  15658. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15659. var _this = this;
  15660. if (onLoad === void 0) { onLoad = null; }
  15661. if (onError === void 0) { onError = null; }
  15662. if (forcedExtension === void 0) { forcedExtension = null; }
  15663. if (createPolynomials === void 0) { createPolynomials = false; }
  15664. var gl = this._gl;
  15665. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15666. texture.isCube = true;
  15667. texture.url = rootUrl;
  15668. texture.generateMipMaps = !noMipmap;
  15669. if (!this._doNotHandleContextLost) {
  15670. texture._extension = forcedExtension;
  15671. texture._files = files;
  15672. }
  15673. var isKTX = false;
  15674. var isDDS = false;
  15675. var lastDot = rootUrl.lastIndexOf('.');
  15676. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15677. if (this._textureFormatInUse) {
  15678. extension = this._textureFormatInUse;
  15679. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15680. isKTX = true;
  15681. }
  15682. else {
  15683. isDDS = (extension === ".dds");
  15684. }
  15685. var onerror = function (request, exception) {
  15686. if (onError && request) {
  15687. onError(request.status + " " + request.statusText, exception);
  15688. }
  15689. };
  15690. if (isKTX) {
  15691. this._loadFile(rootUrl, function (data) {
  15692. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15693. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15694. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15695. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15696. ktx.uploadLevels(_this._gl, !noMipmap);
  15697. _this.setCubeMapTextureParams(gl, loadMipmap);
  15698. texture.width = ktx.pixelWidth;
  15699. texture.height = ktx.pixelHeight;
  15700. texture.isReady = true;
  15701. }, undefined, undefined, true, onerror);
  15702. }
  15703. else if (isDDS) {
  15704. if (files && files.length === 6) {
  15705. this._cascadeLoadFiles(scene, function (imgs) {
  15706. var info;
  15707. var loadMipmap = false;
  15708. var width = 0;
  15709. for (var index = 0; index < imgs.length; index++) {
  15710. var data = imgs[index];
  15711. info = BABYLON.DDSTools.GetDDSInfo(data);
  15712. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15713. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15714. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15715. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15716. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15717. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15718. }
  15719. texture.width = info.width;
  15720. texture.height = info.height;
  15721. texture.type = info.textureType;
  15722. width = info.width;
  15723. }
  15724. _this.setCubeMapTextureParams(gl, loadMipmap);
  15725. texture.isReady = true;
  15726. if (onLoad) {
  15727. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15728. }
  15729. }, files, onError);
  15730. }
  15731. else {
  15732. this._loadFile(rootUrl, function (data) {
  15733. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15734. if (createPolynomials) {
  15735. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15736. }
  15737. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15738. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15740. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15741. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15742. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15743. }
  15744. _this.setCubeMapTextureParams(gl, loadMipmap);
  15745. texture.width = info.width;
  15746. texture.height = info.height;
  15747. texture.isReady = true;
  15748. texture.type = info.textureType;
  15749. if (onLoad) {
  15750. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15751. }
  15752. }, undefined, undefined, true, onerror);
  15753. }
  15754. }
  15755. else {
  15756. if (!files) {
  15757. throw new Error("Cannot load cubemap because files were not defined");
  15758. }
  15759. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15760. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15761. var height = width;
  15762. _this._prepareWorkingCanvas();
  15763. if (!_this._workingCanvas || !_this._workingContext) {
  15764. return;
  15765. }
  15766. _this._workingCanvas.width = width;
  15767. _this._workingCanvas.height = height;
  15768. var faces = [
  15769. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15770. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15771. ];
  15772. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15773. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15774. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15775. for (var index = 0; index < faces.length; index++) {
  15776. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15777. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15778. }
  15779. if (!noMipmap) {
  15780. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15781. }
  15782. _this.setCubeMapTextureParams(gl, !noMipmap);
  15783. texture.width = width;
  15784. texture.height = height;
  15785. texture.isReady = true;
  15786. if (format) {
  15787. texture.format = format;
  15788. }
  15789. texture.onLoadedObservable.notifyObservers(texture);
  15790. texture.onLoadedObservable.clear();
  15791. if (onLoad) {
  15792. onLoad();
  15793. }
  15794. }, files, onError);
  15795. }
  15796. this._internalTexturesCache.push(texture);
  15797. return texture;
  15798. };
  15799. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15804. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15805. // this.resetTextureCache();
  15806. };
  15807. /**
  15808. * Update a raw cube texture
  15809. * @param texture defines the texture to udpdate
  15810. * @param data defines the data to store
  15811. * @param format defines the data format
  15812. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15813. * @param invertY defines if data must be stored with Y axis inverted
  15814. * @param compression defines the compression used (null by default)
  15815. * @param level defines which level of the texture to update
  15816. */
  15817. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15818. if (compression === void 0) { compression = null; }
  15819. if (level === void 0) { level = 0; }
  15820. texture._bufferViewArray = data;
  15821. texture.format = format;
  15822. texture.type = type;
  15823. texture.invertY = invertY;
  15824. texture._compression = compression;
  15825. var gl = this._gl;
  15826. var textureType = this._getWebGLTextureType(type);
  15827. var internalFormat = this._getInternalFormat(format);
  15828. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15829. var needConversion = false;
  15830. if (internalFormat === gl.RGB) {
  15831. internalFormat = gl.RGBA;
  15832. needConversion = true;
  15833. }
  15834. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15835. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15836. if (texture.width % 4 !== 0) {
  15837. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15838. }
  15839. // Data are known to be in +X +Y +Z -X -Y -Z
  15840. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15841. var faceData = data[faceIndex];
  15842. if (compression) {
  15843. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15844. }
  15845. else {
  15846. if (needConversion) {
  15847. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15848. }
  15849. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15850. }
  15851. }
  15852. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15853. if (isPot && texture.generateMipMaps && level === 0) {
  15854. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15855. }
  15856. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15857. // this.resetTextureCache();
  15858. texture.isReady = true;
  15859. };
  15860. /**
  15861. * Creates a new raw cube texture
  15862. * @param data defines the array of data to use to create each face
  15863. * @param size defines the size of the textures
  15864. * @param format defines the format of the data
  15865. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15866. * @param generateMipMaps defines if the engine should generate the mip levels
  15867. * @param invertY defines if data must be stored with Y axis inverted
  15868. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15869. * @param compression defines the compression used (null by default)
  15870. * @returns the cube texture as an InternalTexture
  15871. */
  15872. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15873. if (compression === void 0) { compression = null; }
  15874. var gl = this._gl;
  15875. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15876. texture.isCube = true;
  15877. texture.generateMipMaps = generateMipMaps;
  15878. texture.format = format;
  15879. texture.type = type;
  15880. if (!this._doNotHandleContextLost) {
  15881. texture._bufferViewArray = data;
  15882. }
  15883. var textureType = this._getWebGLTextureType(type);
  15884. var internalFormat = this._getInternalFormat(format);
  15885. if (internalFormat === gl.RGB) {
  15886. internalFormat = gl.RGBA;
  15887. }
  15888. var width = size;
  15889. var height = width;
  15890. texture.width = width;
  15891. texture.height = height;
  15892. // Double check on POT to generate Mips.
  15893. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15894. if (!isPot) {
  15895. generateMipMaps = false;
  15896. }
  15897. // Upload data if needed. The texture won't be ready until then.
  15898. if (data) {
  15899. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15900. }
  15901. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15902. // Filters
  15903. if (data && generateMipMaps) {
  15904. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15905. }
  15906. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15909. }
  15910. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15913. }
  15914. else {
  15915. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15918. }
  15919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15922. return texture;
  15923. };
  15924. /**
  15925. * Creates a new raw cube texture from a specified url
  15926. * @param url defines the url where the data is located
  15927. * @param scene defines the current scene
  15928. * @param size defines the size of the textures
  15929. * @param format defines the format of the data
  15930. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15931. * @param noMipmap defines if the engine should avoid generating the mip levels
  15932. * @param callback defines a callback used to extract texture data from loaded data
  15933. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15934. * @param onLoad defines a callback called when texture is loaded
  15935. * @param onError defines a callback called if there is an error
  15936. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15937. * @param invertY defines if data must be stored with Y axis inverted
  15938. * @returns the cube texture as an InternalTexture
  15939. */
  15940. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15941. var _this = this;
  15942. if (onLoad === void 0) { onLoad = null; }
  15943. if (onError === void 0) { onError = null; }
  15944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15945. if (invertY === void 0) { invertY = false; }
  15946. var gl = this._gl;
  15947. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15948. scene._addPendingData(texture);
  15949. texture.url = url;
  15950. this._internalTexturesCache.push(texture);
  15951. var onerror = function (request, exception) {
  15952. scene._removePendingData(texture);
  15953. if (onError && request) {
  15954. onError(request.status + " " + request.statusText, exception);
  15955. }
  15956. };
  15957. var internalCallback = function (data) {
  15958. var width = texture.width;
  15959. var faceDataArrays = callback(data);
  15960. if (!faceDataArrays) {
  15961. return;
  15962. }
  15963. if (mipmapGenerator) {
  15964. var textureType = _this._getWebGLTextureType(type);
  15965. var internalFormat = _this._getInternalFormat(format);
  15966. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15967. var needConversion = false;
  15968. if (internalFormat === gl.RGB) {
  15969. internalFormat = gl.RGBA;
  15970. needConversion = true;
  15971. }
  15972. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15973. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15974. var mipData = mipmapGenerator(faceDataArrays);
  15975. for (var level = 0; level < mipData.length; level++) {
  15976. var mipSize = width >> level;
  15977. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15978. var mipFaceData = mipData[level][faceIndex];
  15979. if (needConversion) {
  15980. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15981. }
  15982. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15983. }
  15984. }
  15985. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15986. }
  15987. else {
  15988. texture.generateMipMaps = !noMipmap;
  15989. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15990. }
  15991. texture.isReady = true;
  15992. // this.resetTextureCache();
  15993. scene._removePendingData(texture);
  15994. if (onLoad) {
  15995. onLoad();
  15996. }
  15997. };
  15998. this._loadFile(url, function (data) {
  15999. internalCallback(data);
  16000. }, undefined, scene.database, true, onerror);
  16001. return texture;
  16002. };
  16003. ;
  16004. /**
  16005. * Update a raw 3D texture
  16006. * @param texture defines the texture to update
  16007. * @param data defines the data to store
  16008. * @param format defines the data format
  16009. * @param invertY defines if data must be stored with Y axis inverted
  16010. * @param compression defines the used compression (can be null)
  16011. */
  16012. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  16013. if (compression === void 0) { compression = null; }
  16014. var internalFormat = this._getInternalFormat(format);
  16015. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16016. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16017. if (!this._doNotHandleContextLost) {
  16018. texture._bufferView = data;
  16019. texture.format = format;
  16020. texture.invertY = invertY;
  16021. texture._compression = compression;
  16022. }
  16023. if (texture.width % 4 !== 0) {
  16024. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16025. }
  16026. if (compression && data) {
  16027. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16028. }
  16029. else {
  16030. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16031. }
  16032. if (texture.generateMipMaps) {
  16033. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16034. }
  16035. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16036. // this.resetTextureCache();
  16037. texture.isReady = true;
  16038. };
  16039. /**
  16040. * Creates a new raw 3D texture
  16041. * @param data defines the data used to create the texture
  16042. * @param width defines the width of the texture
  16043. * @param height defines the height of the texture
  16044. * @param depth defines the depth of the texture
  16045. * @param format defines the format of the texture
  16046. * @param generateMipMaps defines if the engine must generate mip levels
  16047. * @param invertY defines if data must be stored with Y axis inverted
  16048. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16049. * @param compression defines the compressed used (can be null)
  16050. * @returns a new raw 3D texture (stored in an InternalTexture)
  16051. */
  16052. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16053. if (compression === void 0) { compression = null; }
  16054. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16055. texture.baseWidth = width;
  16056. texture.baseHeight = height;
  16057. texture.baseDepth = depth;
  16058. texture.width = width;
  16059. texture.height = height;
  16060. texture.depth = depth;
  16061. texture.format = format;
  16062. texture.generateMipMaps = generateMipMaps;
  16063. texture.samplingMode = samplingMode;
  16064. texture.is3D = true;
  16065. if (!this._doNotHandleContextLost) {
  16066. texture._bufferView = data;
  16067. }
  16068. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16069. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16070. // Filters
  16071. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16072. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16073. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16074. if (generateMipMaps) {
  16075. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16076. }
  16077. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16078. this._internalTexturesCache.push(texture);
  16079. return texture;
  16080. };
  16081. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16082. var gl = this._gl;
  16083. if (!gl) {
  16084. return;
  16085. }
  16086. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16089. if (!noMipmap && !isCompressed) {
  16090. gl.generateMipmap(gl.TEXTURE_2D);
  16091. }
  16092. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16093. // this.resetTextureCache();
  16094. if (scene) {
  16095. scene._removePendingData(texture);
  16096. }
  16097. texture.onLoadedObservable.notifyObservers(texture);
  16098. texture.onLoadedObservable.clear();
  16099. };
  16100. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16101. var _this = this;
  16102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16103. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16104. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16105. var gl = this._gl;
  16106. if (!gl) {
  16107. return;
  16108. }
  16109. if (!texture._webGLTexture) {
  16110. // this.resetTextureCache();
  16111. if (scene) {
  16112. scene._removePendingData(texture);
  16113. }
  16114. return;
  16115. }
  16116. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16117. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16118. texture.baseWidth = width;
  16119. texture.baseHeight = height;
  16120. texture.width = potWidth;
  16121. texture.height = potHeight;
  16122. texture.isReady = true;
  16123. if (processFunction(potWidth, potHeight, function () {
  16124. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16125. })) {
  16126. // Returning as texture needs extra async steps
  16127. return;
  16128. }
  16129. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16130. };
  16131. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16132. // Create new RGBA data container.
  16133. var rgbaData;
  16134. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16135. rgbaData = new Float32Array(width * height * 4);
  16136. }
  16137. else {
  16138. rgbaData = new Uint32Array(width * height * 4);
  16139. }
  16140. // Convert each pixel.
  16141. for (var x = 0; x < width; x++) {
  16142. for (var y = 0; y < height; y++) {
  16143. var index = (y * width + x) * 3;
  16144. var newIndex = (y * width + x) * 4;
  16145. // Map Old Value to new value.
  16146. rgbaData[newIndex + 0] = rgbData[index + 0];
  16147. rgbaData[newIndex + 1] = rgbData[index + 1];
  16148. rgbaData[newIndex + 2] = rgbData[index + 2];
  16149. // Add fully opaque alpha channel.
  16150. rgbaData[newIndex + 3] = 1;
  16151. }
  16152. }
  16153. return rgbaData;
  16154. };
  16155. /** @hidden */
  16156. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16157. var gl = this._gl;
  16158. if (texture._framebuffer) {
  16159. gl.deleteFramebuffer(texture._framebuffer);
  16160. texture._framebuffer = null;
  16161. }
  16162. if (texture._depthStencilBuffer) {
  16163. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16164. texture._depthStencilBuffer = null;
  16165. }
  16166. if (texture._MSAAFramebuffer) {
  16167. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16168. texture._MSAAFramebuffer = null;
  16169. }
  16170. if (texture._MSAARenderBuffer) {
  16171. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16172. texture._MSAARenderBuffer = null;
  16173. }
  16174. };
  16175. /** @hidden */
  16176. Engine.prototype._releaseTexture = function (texture) {
  16177. var gl = this._gl;
  16178. this._releaseFramebufferObjects(texture);
  16179. gl.deleteTexture(texture._webGLTexture);
  16180. // Unbind channels
  16181. this.unbindAllTextures();
  16182. var index = this._internalTexturesCache.indexOf(texture);
  16183. if (index !== -1) {
  16184. this._internalTexturesCache.splice(index, 1);
  16185. }
  16186. // Integrated fixed lod samplers.
  16187. if (texture._lodTextureHigh) {
  16188. texture._lodTextureHigh.dispose();
  16189. }
  16190. if (texture._lodTextureMid) {
  16191. texture._lodTextureMid.dispose();
  16192. }
  16193. if (texture._lodTextureLow) {
  16194. texture._lodTextureLow.dispose();
  16195. }
  16196. // Set output texture of post process to null if the texture has been released/disposed
  16197. this.scenes.forEach(function (scene) {
  16198. scene.postProcesses.forEach(function (postProcess) {
  16199. if (postProcess._outputTexture == texture) {
  16200. postProcess._outputTexture = null;
  16201. }
  16202. });
  16203. scene.cameras.forEach(function (camera) {
  16204. camera._postProcesses.forEach(function (postProcess) {
  16205. if (postProcess) {
  16206. if (postProcess._outputTexture == texture) {
  16207. postProcess._outputTexture = null;
  16208. }
  16209. }
  16210. });
  16211. });
  16212. });
  16213. };
  16214. Engine.prototype.setProgram = function (program) {
  16215. if (this._currentProgram !== program) {
  16216. this._gl.useProgram(program);
  16217. this._currentProgram = program;
  16218. }
  16219. };
  16220. /**
  16221. * Binds an effect to the webGL context
  16222. * @param effect defines the effect to bind
  16223. */
  16224. Engine.prototype.bindSamplers = function (effect) {
  16225. this.setProgram(effect.getProgram());
  16226. var samplers = effect.getSamplers();
  16227. for (var index = 0; index < samplers.length; index++) {
  16228. var uniform = effect.getUniform(samplers[index]);
  16229. if (uniform) {
  16230. this._boundUniforms[index] = uniform;
  16231. }
  16232. }
  16233. this._currentEffect = null;
  16234. };
  16235. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16236. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16237. return;
  16238. }
  16239. // Remove
  16240. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16241. // Bind last to it
  16242. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16243. // Bind to dummy
  16244. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16245. };
  16246. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16247. if (!internalTexture) {
  16248. return -1;
  16249. }
  16250. internalTexture._initialSlot = channel;
  16251. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16252. if (channel !== internalTexture._designatedSlot) {
  16253. this._textureCollisions.addCount(1, false);
  16254. }
  16255. }
  16256. else {
  16257. if (channel !== internalTexture._designatedSlot) {
  16258. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16259. return internalTexture._designatedSlot;
  16260. }
  16261. else {
  16262. // No slot for this texture, let's pick a new one (if we find a free slot)
  16263. if (this._nextFreeTextureSlots.length) {
  16264. return this._nextFreeTextureSlots[0];
  16265. }
  16266. // We need to recycle the oldest bound texture, sorry.
  16267. this._textureCollisions.addCount(1, false);
  16268. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16269. }
  16270. }
  16271. }
  16272. return channel;
  16273. };
  16274. Engine.prototype._linkTrackers = function (previous, next) {
  16275. previous.next = next;
  16276. next.previous = previous;
  16277. };
  16278. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16279. var currentSlot = internalTexture._designatedSlot;
  16280. if (currentSlot === -1) {
  16281. return -1;
  16282. }
  16283. internalTexture._designatedSlot = -1;
  16284. if (this.disableTextureBindingOptimization) {
  16285. return -1;
  16286. }
  16287. // Remove from bound list
  16288. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16289. // Free the slot
  16290. this._boundTexturesCache[currentSlot] = null;
  16291. this._nextFreeTextureSlots.push(currentSlot);
  16292. return currentSlot;
  16293. };
  16294. Engine.prototype._activateCurrentTexture = function () {
  16295. if (this._currentTextureChannel !== this._activeChannel) {
  16296. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16297. this._currentTextureChannel = this._activeChannel;
  16298. }
  16299. };
  16300. /** @hidden */
  16301. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16302. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16303. if (force === void 0) { force = false; }
  16304. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16305. this._activeChannel = texture._designatedSlot;
  16306. }
  16307. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16308. var isTextureForRendering = texture && texture._initialSlot > -1;
  16309. if (currentTextureBound !== texture || force) {
  16310. if (currentTextureBound) {
  16311. this._removeDesignatedSlot(currentTextureBound);
  16312. }
  16313. this._activateCurrentTexture();
  16314. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16315. this._boundTexturesCache[this._activeChannel] = texture;
  16316. if (texture) {
  16317. if (!this.disableTextureBindingOptimization) {
  16318. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16319. if (slotIndex > -1) {
  16320. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16321. }
  16322. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16323. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16324. }
  16325. texture._designatedSlot = this._activeChannel;
  16326. }
  16327. }
  16328. else if (forTextureDataUpdate) {
  16329. this._activateCurrentTexture();
  16330. }
  16331. if (isTextureForRendering && !forTextureDataUpdate) {
  16332. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16333. }
  16334. };
  16335. /** @hidden */
  16336. Engine.prototype._bindTexture = function (channel, texture) {
  16337. if (channel < 0) {
  16338. return;
  16339. }
  16340. if (texture) {
  16341. channel = this._getCorrectTextureChannel(channel, texture);
  16342. }
  16343. this._activeChannel = channel;
  16344. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16345. };
  16346. /**
  16347. * Sets a texture to the webGL context from a postprocess
  16348. * @param channel defines the channel to use
  16349. * @param postProcess defines the source postprocess
  16350. */
  16351. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16352. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16353. };
  16354. /**
  16355. * Binds the output of the passed in post process to the texture channel specified
  16356. * @param channel The channel the texture should be bound to
  16357. * @param postProcess The post process which's output should be bound
  16358. */
  16359. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16360. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16361. };
  16362. /**
  16363. * Unbind all textures from the webGL context
  16364. */
  16365. Engine.prototype.unbindAllTextures = function () {
  16366. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16367. this._activeChannel = channel;
  16368. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16369. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16370. if (this.webGLVersion > 1) {
  16371. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16372. }
  16373. }
  16374. };
  16375. /**
  16376. * Sets a texture to the according uniform.
  16377. * @param channel The texture channel
  16378. * @param uniform The uniform to set
  16379. * @param texture The texture to apply
  16380. */
  16381. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16382. if (channel < 0) {
  16383. return;
  16384. }
  16385. if (uniform) {
  16386. this._boundUniforms[channel] = uniform;
  16387. }
  16388. this._setTexture(channel, texture);
  16389. };
  16390. /**
  16391. * Sets a depth stencil texture from a render target to the according uniform.
  16392. * @param channel The texture channel
  16393. * @param uniform The uniform to set
  16394. * @param texture The render target texture containing the depth stencil texture to apply
  16395. */
  16396. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16397. if (channel < 0) {
  16398. return;
  16399. }
  16400. if (uniform) {
  16401. this._boundUniforms[channel] = uniform;
  16402. }
  16403. if (!texture || !texture.depthStencilTexture) {
  16404. this._setTexture(channel, null);
  16405. }
  16406. else {
  16407. this._setTexture(channel, texture, false, true);
  16408. }
  16409. };
  16410. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16411. var uniform = this._boundUniforms[sourceSlot];
  16412. if (uniform._currentState === destination) {
  16413. return;
  16414. }
  16415. this._gl.uniform1i(uniform, destination);
  16416. uniform._currentState = destination;
  16417. };
  16418. Engine.prototype._getTextureWrapMode = function (mode) {
  16419. switch (mode) {
  16420. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16421. return this._gl.REPEAT;
  16422. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16423. return this._gl.CLAMP_TO_EDGE;
  16424. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16425. return this._gl.MIRRORED_REPEAT;
  16426. }
  16427. return this._gl.REPEAT;
  16428. };
  16429. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16430. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16431. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16432. // Not ready?
  16433. if (!texture) {
  16434. if (this._boundTexturesCache[channel] != null) {
  16435. this._activeChannel = channel;
  16436. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16437. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16438. if (this.webGLVersion > 1) {
  16439. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16440. }
  16441. }
  16442. return false;
  16443. }
  16444. // Video
  16445. if (texture.video) {
  16446. this._activeChannel = channel;
  16447. texture.update();
  16448. }
  16449. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16450. texture.delayLoad();
  16451. return false;
  16452. }
  16453. var internalTexture;
  16454. if (depthStencilTexture) {
  16455. internalTexture = texture.depthStencilTexture;
  16456. }
  16457. else if (texture.isReady()) {
  16458. internalTexture = texture.getInternalTexture();
  16459. }
  16460. else if (texture.isCube) {
  16461. internalTexture = this.emptyCubeTexture;
  16462. }
  16463. else if (texture.is3D) {
  16464. internalTexture = this.emptyTexture3D;
  16465. }
  16466. else {
  16467. internalTexture = this.emptyTexture;
  16468. }
  16469. if (!isPartOfTextureArray) {
  16470. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16471. }
  16472. var needToBind = true;
  16473. if (this._boundTexturesCache[channel] === internalTexture) {
  16474. this._moveBoundTextureOnTop(internalTexture);
  16475. if (!isPartOfTextureArray) {
  16476. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16477. }
  16478. needToBind = false;
  16479. }
  16480. this._activeChannel = channel;
  16481. if (internalTexture && internalTexture.is3D) {
  16482. if (needToBind) {
  16483. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16484. }
  16485. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16486. internalTexture._cachedWrapU = texture.wrapU;
  16487. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16488. }
  16489. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16490. internalTexture._cachedWrapV = texture.wrapV;
  16491. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16492. }
  16493. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16494. internalTexture._cachedWrapR = texture.wrapR;
  16495. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16496. }
  16497. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16498. }
  16499. else if (internalTexture && internalTexture.isCube) {
  16500. if (needToBind) {
  16501. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16502. }
  16503. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16504. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16505. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16506. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16507. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16508. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16509. }
  16510. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16511. }
  16512. else {
  16513. if (needToBind) {
  16514. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16515. }
  16516. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16517. internalTexture._cachedWrapU = texture.wrapU;
  16518. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16519. }
  16520. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16521. internalTexture._cachedWrapV = texture.wrapV;
  16522. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16523. }
  16524. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16525. }
  16526. return true;
  16527. };
  16528. /**
  16529. * Sets an array of texture to the webGL context
  16530. * @param channel defines the channel where the texture array must be set
  16531. * @param uniform defines the associated uniform location
  16532. * @param textures defines the array of textures to bind
  16533. */
  16534. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16535. if (channel < 0 || !uniform) {
  16536. return;
  16537. }
  16538. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16539. this._textureUnits = new Int32Array(textures.length);
  16540. }
  16541. for (var i = 0; i < textures.length; i++) {
  16542. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16543. }
  16544. this._gl.uniform1iv(uniform, this._textureUnits);
  16545. for (var index = 0; index < textures.length; index++) {
  16546. this._setTexture(this._textureUnits[index], textures[index], true);
  16547. }
  16548. };
  16549. /** @hidden */
  16550. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16551. var internalTexture = texture.getInternalTexture();
  16552. if (!internalTexture) {
  16553. return;
  16554. }
  16555. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16556. var value = texture.anisotropicFilteringLevel;
  16557. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16558. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16559. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16560. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16561. }
  16562. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16563. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16564. internalTexture._cachedAnisotropicFilteringLevel = value;
  16565. }
  16566. };
  16567. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16568. this._bindTextureDirectly(target, texture, true, true);
  16569. this._gl.texParameterf(target, parameter, value);
  16570. };
  16571. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16572. if (texture) {
  16573. this._bindTextureDirectly(target, texture, true, true);
  16574. }
  16575. this._gl.texParameteri(target, parameter, value);
  16576. };
  16577. /**
  16578. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16579. * @param x defines the x coordinate of the rectangle where pixels must be read
  16580. * @param y defines the y coordinate of the rectangle where pixels must be read
  16581. * @param width defines the width of the rectangle where pixels must be read
  16582. * @param height defines the height of the rectangle where pixels must be read
  16583. * @returns a Uint8Array containing RGBA colors
  16584. */
  16585. Engine.prototype.readPixels = function (x, y, width, height) {
  16586. var data = new Uint8Array(height * width * 4);
  16587. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16588. return data;
  16589. };
  16590. /**
  16591. * Add an externaly attached data from its key.
  16592. * This method call will fail and return false, if such key already exists.
  16593. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16594. * @param key the unique key that identifies the data
  16595. * @param data the data object to associate to the key for this Engine instance
  16596. * @return true if no such key were already present and the data was added successfully, false otherwise
  16597. */
  16598. Engine.prototype.addExternalData = function (key, data) {
  16599. if (!this._externalData) {
  16600. this._externalData = new BABYLON.StringDictionary();
  16601. }
  16602. return this._externalData.add(key, data);
  16603. };
  16604. /**
  16605. * Get an externaly attached data from its key
  16606. * @param key the unique key that identifies the data
  16607. * @return the associated data, if present (can be null), or undefined if not present
  16608. */
  16609. Engine.prototype.getExternalData = function (key) {
  16610. if (!this._externalData) {
  16611. this._externalData = new BABYLON.StringDictionary();
  16612. }
  16613. return this._externalData.get(key);
  16614. };
  16615. /**
  16616. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16617. * @param key the unique key that identifies the data
  16618. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16619. * @return the associated data, can be null if the factory returned null.
  16620. */
  16621. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16622. if (!this._externalData) {
  16623. this._externalData = new BABYLON.StringDictionary();
  16624. }
  16625. return this._externalData.getOrAddWithFactory(key, factory);
  16626. };
  16627. /**
  16628. * Remove an externaly attached data from the Engine instance
  16629. * @param key the unique key that identifies the data
  16630. * @return true if the data was successfully removed, false if it doesn't exist
  16631. */
  16632. Engine.prototype.removeExternalData = function (key) {
  16633. if (!this._externalData) {
  16634. this._externalData = new BABYLON.StringDictionary();
  16635. }
  16636. return this._externalData.remove(key);
  16637. };
  16638. /**
  16639. * Unbind all vertex attributes from the webGL context
  16640. */
  16641. Engine.prototype.unbindAllAttributes = function () {
  16642. if (this._mustWipeVertexAttributes) {
  16643. this._mustWipeVertexAttributes = false;
  16644. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16645. this._gl.disableVertexAttribArray(i);
  16646. this._vertexAttribArraysEnabled[i] = false;
  16647. this._currentBufferPointers[i].active = false;
  16648. }
  16649. return;
  16650. }
  16651. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16652. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16653. continue;
  16654. }
  16655. this._gl.disableVertexAttribArray(i);
  16656. this._vertexAttribArraysEnabled[i] = false;
  16657. this._currentBufferPointers[i].active = false;
  16658. }
  16659. };
  16660. /**
  16661. * 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
  16662. */
  16663. Engine.prototype.releaseEffects = function () {
  16664. for (var name in this._compiledEffects) {
  16665. this._deleteProgram(this._compiledEffects[name]._program);
  16666. }
  16667. this._compiledEffects = {};
  16668. };
  16669. /**
  16670. * Dispose and release all associated resources
  16671. */
  16672. Engine.prototype.dispose = function () {
  16673. this.hideLoadingUI();
  16674. this.stopRenderLoop();
  16675. // Release postProcesses
  16676. while (this.postProcesses.length) {
  16677. this.postProcesses[0].dispose();
  16678. }
  16679. // Empty texture
  16680. if (this._emptyTexture) {
  16681. this._releaseTexture(this._emptyTexture);
  16682. this._emptyTexture = null;
  16683. }
  16684. if (this._emptyCubeTexture) {
  16685. this._releaseTexture(this._emptyCubeTexture);
  16686. this._emptyCubeTexture = null;
  16687. }
  16688. // Rescale PP
  16689. if (this._rescalePostProcess) {
  16690. this._rescalePostProcess.dispose();
  16691. }
  16692. // Release scenes
  16693. while (this.scenes.length) {
  16694. this.scenes[0].dispose();
  16695. }
  16696. // Release audio engine
  16697. if (Engine.audioEngine) {
  16698. Engine.audioEngine.dispose();
  16699. }
  16700. // Release effects
  16701. this.releaseEffects();
  16702. // Unbind
  16703. this.unbindAllAttributes();
  16704. this._boundUniforms = [];
  16705. if (this._dummyFramebuffer) {
  16706. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16707. }
  16708. //WebVR
  16709. this.disableVR();
  16710. // Events
  16711. if (BABYLON.Tools.IsWindowObjectExist()) {
  16712. window.removeEventListener("blur", this._onBlur);
  16713. window.removeEventListener("focus", this._onFocus);
  16714. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16715. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16716. if (this._renderingCanvas) {
  16717. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16718. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16719. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16720. if (!this._doNotHandleContextLost) {
  16721. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16722. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16723. }
  16724. }
  16725. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16726. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16727. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16728. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16729. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16730. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16731. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16732. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16733. if (this._onVrDisplayConnect) {
  16734. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16735. if (this._onVrDisplayDisconnect) {
  16736. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16737. }
  16738. if (this._onVrDisplayPresentChange) {
  16739. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16740. }
  16741. this._onVrDisplayConnect = null;
  16742. this._onVrDisplayDisconnect = null;
  16743. }
  16744. }
  16745. // Remove from Instances
  16746. var index = Engine.Instances.indexOf(this);
  16747. if (index >= 0) {
  16748. Engine.Instances.splice(index, 1);
  16749. }
  16750. this._workingCanvas = null;
  16751. this._workingContext = null;
  16752. this._currentBufferPointers = [];
  16753. this._renderingCanvas = null;
  16754. this._currentProgram = null;
  16755. this._bindedRenderFunction = null;
  16756. this.onResizeObservable.clear();
  16757. this.onCanvasBlurObservable.clear();
  16758. this.onCanvasFocusObservable.clear();
  16759. this.onCanvasPointerOutObservable.clear();
  16760. this.onBeginFrameObservable.clear();
  16761. this.onEndFrameObservable.clear();
  16762. BABYLON.Effect.ResetCache();
  16763. // Abort active requests
  16764. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16765. var request = _a[_i];
  16766. request.abort();
  16767. }
  16768. };
  16769. // Loading screen
  16770. /**
  16771. * Display the loading screen
  16772. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16773. */
  16774. Engine.prototype.displayLoadingUI = function () {
  16775. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16776. return;
  16777. }
  16778. var loadingScreen = this.loadingScreen;
  16779. if (loadingScreen) {
  16780. loadingScreen.displayLoadingUI();
  16781. }
  16782. };
  16783. /**
  16784. * Hide the loading screen
  16785. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16786. */
  16787. Engine.prototype.hideLoadingUI = function () {
  16788. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16789. return;
  16790. }
  16791. var loadingScreen = this.loadingScreen;
  16792. if (loadingScreen) {
  16793. loadingScreen.hideLoadingUI();
  16794. }
  16795. };
  16796. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16797. /**
  16798. * Gets the current loading screen object
  16799. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16800. */
  16801. get: function () {
  16802. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16803. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16804. return this._loadingScreen;
  16805. },
  16806. /**
  16807. * Sets the current loading screen object
  16808. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16809. */
  16810. set: function (loadingScreen) {
  16811. this._loadingScreen = loadingScreen;
  16812. },
  16813. enumerable: true,
  16814. configurable: true
  16815. });
  16816. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16817. /**
  16818. * Sets the current loading screen text
  16819. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16820. */
  16821. set: function (text) {
  16822. this.loadingScreen.loadingUIText = text;
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16828. /**
  16829. * Sets the current loading screen background color
  16830. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16831. */
  16832. set: function (color) {
  16833. this.loadingScreen.loadingUIBackgroundColor = color;
  16834. },
  16835. enumerable: true,
  16836. configurable: true
  16837. });
  16838. /**
  16839. * Attach a new callback raised when context lost event is fired
  16840. * @param callback defines the callback to call
  16841. */
  16842. Engine.prototype.attachContextLostEvent = function (callback) {
  16843. if (this._renderingCanvas) {
  16844. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16845. }
  16846. };
  16847. /**
  16848. * Attach a new callback raised when context restored event is fired
  16849. * @param callback defines the callback to call
  16850. */
  16851. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16852. if (this._renderingCanvas) {
  16853. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16854. }
  16855. };
  16856. /**
  16857. * Gets the source code of the vertex shader associated with a specific webGL program
  16858. * @param program defines the program to use
  16859. * @returns a string containing the source code of the vertex shader associated with the program
  16860. */
  16861. Engine.prototype.getVertexShaderSource = function (program) {
  16862. var shaders = this._gl.getAttachedShaders(program);
  16863. if (!shaders) {
  16864. return null;
  16865. }
  16866. return this._gl.getShaderSource(shaders[0]);
  16867. };
  16868. /**
  16869. * Gets the source code of the fragment shader associated with a specific webGL program
  16870. * @param program defines the program to use
  16871. * @returns a string containing the source code of the fragment shader associated with the program
  16872. */
  16873. Engine.prototype.getFragmentShaderSource = function (program) {
  16874. var shaders = this._gl.getAttachedShaders(program);
  16875. if (!shaders) {
  16876. return null;
  16877. }
  16878. return this._gl.getShaderSource(shaders[1]);
  16879. };
  16880. /**
  16881. * Get the current error code of the webGL context
  16882. * @returns the error code
  16883. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16884. */
  16885. Engine.prototype.getError = function () {
  16886. return this._gl.getError();
  16887. };
  16888. // FPS
  16889. /**
  16890. * Gets the current framerate
  16891. * @returns a number representing the framerate
  16892. */
  16893. Engine.prototype.getFps = function () {
  16894. return this._fps;
  16895. };
  16896. /**
  16897. * Gets the time spent between current and previous frame
  16898. * @returns a number representing the delta time in ms
  16899. */
  16900. Engine.prototype.getDeltaTime = function () {
  16901. return this._deltaTime;
  16902. };
  16903. Engine.prototype._measureFps = function () {
  16904. this._performanceMonitor.sampleFrame();
  16905. this._fps = this._performanceMonitor.averageFPS;
  16906. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16907. };
  16908. /** @hidden */
  16909. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16910. if (faceIndex === void 0) { faceIndex = -1; }
  16911. var gl = this._gl;
  16912. if (!this._dummyFramebuffer) {
  16913. var dummy = gl.createFramebuffer();
  16914. if (!dummy) {
  16915. throw new Error("Unable to create dummy framebuffer");
  16916. }
  16917. this._dummyFramebuffer = dummy;
  16918. }
  16919. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16920. if (faceIndex > -1) {
  16921. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16922. }
  16923. else {
  16924. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16925. }
  16926. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16927. var buffer;
  16928. switch (readType) {
  16929. case gl.UNSIGNED_BYTE:
  16930. buffer = new Uint8Array(4 * width * height);
  16931. readType = gl.UNSIGNED_BYTE;
  16932. break;
  16933. default:
  16934. buffer = new Float32Array(4 * width * height);
  16935. readType = gl.FLOAT;
  16936. break;
  16937. }
  16938. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16939. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16940. return buffer;
  16941. };
  16942. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16943. if (this._webGLVersion > 1) {
  16944. return this._caps.colorBufferFloat;
  16945. }
  16946. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16947. };
  16948. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16949. if (this._webGLVersion > 1) {
  16950. return this._caps.colorBufferFloat;
  16951. }
  16952. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16953. };
  16954. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16955. Engine.prototype._canRenderToFramebuffer = function (type) {
  16956. var gl = this._gl;
  16957. //clear existing errors
  16958. while (gl.getError() !== gl.NO_ERROR) { }
  16959. var successful = true;
  16960. var texture = gl.createTexture();
  16961. gl.bindTexture(gl.TEXTURE_2D, texture);
  16962. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16965. var fb = gl.createFramebuffer();
  16966. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16967. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16968. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16969. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16970. successful = successful && (gl.getError() === gl.NO_ERROR);
  16971. //try render by clearing frame buffer's color buffer
  16972. if (successful) {
  16973. gl.clear(gl.COLOR_BUFFER_BIT);
  16974. successful = successful && (gl.getError() === gl.NO_ERROR);
  16975. }
  16976. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16977. if (successful) {
  16978. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16979. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16980. var readFormat = gl.RGBA;
  16981. var readType = gl.UNSIGNED_BYTE;
  16982. var buffer = new Uint8Array(4);
  16983. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16984. successful = successful && (gl.getError() === gl.NO_ERROR);
  16985. }
  16986. //clean up
  16987. gl.deleteTexture(texture);
  16988. gl.deleteFramebuffer(fb);
  16989. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16990. //clear accumulated errors
  16991. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16992. return successful;
  16993. };
  16994. /** @hidden */
  16995. Engine.prototype._getWebGLTextureType = function (type) {
  16996. if (type === Engine.TEXTURETYPE_FLOAT) {
  16997. return this._gl.FLOAT;
  16998. }
  16999. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17000. // Add Half Float Constant.
  17001. return this._gl.HALF_FLOAT_OES;
  17002. }
  17003. return this._gl.UNSIGNED_BYTE;
  17004. };
  17005. ;
  17006. Engine.prototype._getInternalFormat = function (format) {
  17007. var internalFormat = this._gl.RGBA;
  17008. switch (format) {
  17009. case Engine.TEXTUREFORMAT_ALPHA:
  17010. internalFormat = this._gl.ALPHA;
  17011. break;
  17012. case Engine.TEXTUREFORMAT_LUMINANCE:
  17013. internalFormat = this._gl.LUMINANCE;
  17014. break;
  17015. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17016. internalFormat = this._gl.LUMINANCE_ALPHA;
  17017. break;
  17018. case Engine.TEXTUREFORMAT_RGB:
  17019. case Engine.TEXTUREFORMAT_RGB32F:
  17020. internalFormat = this._gl.RGB;
  17021. break;
  17022. case Engine.TEXTUREFORMAT_RGBA:
  17023. case Engine.TEXTUREFORMAT_RGBA32F:
  17024. internalFormat = this._gl.RGBA;
  17025. break;
  17026. case Engine.TEXTUREFORMAT_R32F:
  17027. internalFormat = this._gl.RED;
  17028. break;
  17029. case Engine.TEXTUREFORMAT_RG32F:
  17030. internalFormat = this._gl.RG;
  17031. break;
  17032. }
  17033. return internalFormat;
  17034. };
  17035. /** @hidden */
  17036. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17037. if (this._webGLVersion === 1) {
  17038. if (format !== undefined) {
  17039. switch (format) {
  17040. case Engine.TEXTUREFORMAT_LUMINANCE:
  17041. return this._gl.LUMINANCE;
  17042. case Engine.TEXTUREFORMAT_ALPHA:
  17043. return this._gl.ALPHA;
  17044. }
  17045. }
  17046. return this._gl.RGBA;
  17047. }
  17048. if (type === Engine.TEXTURETYPE_FLOAT) {
  17049. if (format !== undefined) {
  17050. switch (format) {
  17051. case Engine.TEXTUREFORMAT_R32F:
  17052. return this._gl.R32F;
  17053. case Engine.TEXTUREFORMAT_RG32F:
  17054. return this._gl.RG32F;
  17055. case Engine.TEXTUREFORMAT_RGB32F:
  17056. return this._gl.RGB32F;
  17057. }
  17058. }
  17059. return this._gl.RGBA32F;
  17060. }
  17061. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17062. return this._gl.RGBA16F;
  17063. }
  17064. if (format !== undefined) {
  17065. switch (format) {
  17066. case Engine.TEXTUREFORMAT_LUMINANCE:
  17067. return this._gl.LUMINANCE;
  17068. case Engine.TEXTUREFORMAT_RGB:
  17069. return this._gl.RGB;
  17070. case Engine.TEXTUREFORMAT_ALPHA:
  17071. return this._gl.ALPHA;
  17072. }
  17073. }
  17074. return this._gl.RGBA;
  17075. };
  17076. ;
  17077. /** @hidden */
  17078. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17079. if (type === Engine.TEXTURETYPE_FLOAT) {
  17080. return this._gl.RGBA32F;
  17081. }
  17082. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17083. return this._gl.RGBA16F;
  17084. }
  17085. return this._gl.RGBA8;
  17086. };
  17087. ;
  17088. /**
  17089. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17090. * @return the new query
  17091. */
  17092. Engine.prototype.createQuery = function () {
  17093. return this._gl.createQuery();
  17094. };
  17095. /**
  17096. * Delete and release a webGL query
  17097. * @param query defines the query to delete
  17098. * @return the current engine
  17099. */
  17100. Engine.prototype.deleteQuery = function (query) {
  17101. this._gl.deleteQuery(query);
  17102. return this;
  17103. };
  17104. /**
  17105. * Check if a given query has resolved and got its value
  17106. * @param query defines the query to check
  17107. * @returns true if the query got its value
  17108. */
  17109. Engine.prototype.isQueryResultAvailable = function (query) {
  17110. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17111. };
  17112. /**
  17113. * Gets the value of a given query
  17114. * @param query defines the query to check
  17115. * @returns the value of the query
  17116. */
  17117. Engine.prototype.getQueryResult = function (query) {
  17118. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17119. };
  17120. /**
  17121. * Initiates an occlusion query
  17122. * @param algorithmType defines the algorithm to use
  17123. * @param query defines the query to use
  17124. * @returns the current engine
  17125. * @see http://doc.babylonjs.com/features/occlusionquery
  17126. */
  17127. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17128. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17129. this._gl.beginQuery(glAlgorithm, query);
  17130. return this;
  17131. };
  17132. /**
  17133. * Ends an occlusion query
  17134. * @see http://doc.babylonjs.com/features/occlusionquery
  17135. * @param algorithmType defines the algorithm to use
  17136. * @returns the current engine
  17137. */
  17138. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17139. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17140. this._gl.endQuery(glAlgorithm);
  17141. return this;
  17142. };
  17143. /* Time queries */
  17144. Engine.prototype._createTimeQuery = function () {
  17145. var timerQuery = this._caps.timerQuery;
  17146. if (timerQuery.createQueryEXT) {
  17147. return timerQuery.createQueryEXT();
  17148. }
  17149. return this.createQuery();
  17150. };
  17151. Engine.prototype._deleteTimeQuery = function (query) {
  17152. var timerQuery = this._caps.timerQuery;
  17153. if (timerQuery.deleteQueryEXT) {
  17154. timerQuery.deleteQueryEXT(query);
  17155. return;
  17156. }
  17157. this.deleteQuery(query);
  17158. };
  17159. Engine.prototype._getTimeQueryResult = function (query) {
  17160. var timerQuery = this._caps.timerQuery;
  17161. if (timerQuery.getQueryObjectEXT) {
  17162. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17163. }
  17164. return this.getQueryResult(query);
  17165. };
  17166. Engine.prototype._getTimeQueryAvailability = function (query) {
  17167. var timerQuery = this._caps.timerQuery;
  17168. if (timerQuery.getQueryObjectEXT) {
  17169. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17170. }
  17171. return this.isQueryResultAvailable(query);
  17172. };
  17173. /**
  17174. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17175. * Please note that only one query can be issued at a time
  17176. * @returns a time token used to track the time span
  17177. */
  17178. Engine.prototype.startTimeQuery = function () {
  17179. var timerQuery = this._caps.timerQuery;
  17180. if (!timerQuery) {
  17181. return null;
  17182. }
  17183. var token = new BABYLON._TimeToken();
  17184. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17185. if (this._caps.canUseTimestampForTimerQuery) {
  17186. token._startTimeQuery = this._createTimeQuery();
  17187. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17188. }
  17189. else {
  17190. if (this._currentNonTimestampToken) {
  17191. return this._currentNonTimestampToken;
  17192. }
  17193. token._timeElapsedQuery = this._createTimeQuery();
  17194. if (timerQuery.beginQueryEXT) {
  17195. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17196. }
  17197. else {
  17198. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17199. }
  17200. this._currentNonTimestampToken = token;
  17201. }
  17202. return token;
  17203. };
  17204. /**
  17205. * Ends a time query
  17206. * @param token defines the token used to measure the time span
  17207. * @returns the time spent (in ns)
  17208. */
  17209. Engine.prototype.endTimeQuery = function (token) {
  17210. var timerQuery = this._caps.timerQuery;
  17211. if (!timerQuery || !token) {
  17212. return -1;
  17213. }
  17214. if (this._caps.canUseTimestampForTimerQuery) {
  17215. if (!token._startTimeQuery) {
  17216. return -1;
  17217. }
  17218. if (!token._endTimeQuery) {
  17219. token._endTimeQuery = this._createTimeQuery();
  17220. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17221. }
  17222. }
  17223. else if (!token._timeElapsedQueryEnded) {
  17224. if (!token._timeElapsedQuery) {
  17225. return -1;
  17226. }
  17227. if (timerQuery.endQueryEXT) {
  17228. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17229. }
  17230. else {
  17231. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17232. }
  17233. token._timeElapsedQueryEnded = true;
  17234. }
  17235. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17236. var available = false;
  17237. if (token._endTimeQuery) {
  17238. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17239. }
  17240. else if (token._timeElapsedQuery) {
  17241. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17242. }
  17243. if (available && !disjoint) {
  17244. var result = 0;
  17245. if (this._caps.canUseTimestampForTimerQuery) {
  17246. if (!token._startTimeQuery || !token._endTimeQuery) {
  17247. return -1;
  17248. }
  17249. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17250. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17251. result = timeEnd - timeStart;
  17252. this._deleteTimeQuery(token._startTimeQuery);
  17253. this._deleteTimeQuery(token._endTimeQuery);
  17254. token._startTimeQuery = null;
  17255. token._endTimeQuery = null;
  17256. }
  17257. else {
  17258. if (!token._timeElapsedQuery) {
  17259. return -1;
  17260. }
  17261. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17262. this._deleteTimeQuery(token._timeElapsedQuery);
  17263. token._timeElapsedQuery = null;
  17264. token._timeElapsedQueryEnded = false;
  17265. this._currentNonTimestampToken = null;
  17266. }
  17267. return result;
  17268. }
  17269. return -1;
  17270. };
  17271. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17272. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17273. };
  17274. // Transform feedback
  17275. /**
  17276. * Creates a webGL transform feedback object
  17277. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17278. * @returns the webGL transform feedback object
  17279. */
  17280. Engine.prototype.createTransformFeedback = function () {
  17281. return this._gl.createTransformFeedback();
  17282. };
  17283. /**
  17284. * Delete a webGL transform feedback object
  17285. * @param value defines the webGL transform feedback object to delete
  17286. */
  17287. Engine.prototype.deleteTransformFeedback = function (value) {
  17288. this._gl.deleteTransformFeedback(value);
  17289. };
  17290. /**
  17291. * Bind a webGL transform feedback object to the webgl context
  17292. * @param value defines the webGL transform feedback object to bind
  17293. */
  17294. Engine.prototype.bindTransformFeedback = function (value) {
  17295. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17296. };
  17297. /**
  17298. * Begins a transform feedback operation
  17299. * @param usePoints defines if points or triangles must be used
  17300. */
  17301. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17302. if (usePoints === void 0) { usePoints = true; }
  17303. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17304. };
  17305. /**
  17306. * Ends a transform feedback operation
  17307. */
  17308. Engine.prototype.endTransformFeedback = function () {
  17309. this._gl.endTransformFeedback();
  17310. };
  17311. /**
  17312. * Specify the varyings to use with transform feedback
  17313. * @param program defines the associated webGL program
  17314. * @param value defines the list of strings representing the varying names
  17315. */
  17316. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17317. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17318. };
  17319. /**
  17320. * Bind a webGL buffer for a transform feedback operation
  17321. * @param value defines the webGL buffer to bind
  17322. */
  17323. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17324. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17325. };
  17326. /** @hidden */
  17327. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17328. var _this = this;
  17329. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17330. this._activeRequests.push(request);
  17331. request.onCompleteObservable.add(function (request) {
  17332. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17333. });
  17334. return request;
  17335. };
  17336. /** @hidden */
  17337. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17338. var _this = this;
  17339. return new Promise(function (resolve, reject) {
  17340. _this._loadFile(url, function (data) {
  17341. resolve(data);
  17342. }, undefined, database, useArrayBuffer, function (request, exception) {
  17343. reject(exception);
  17344. });
  17345. });
  17346. };
  17347. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17348. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17349. var onload = function (data) {
  17350. loadedFiles[index] = data;
  17351. loadedFiles._internalCount++;
  17352. if (loadedFiles._internalCount === 6) {
  17353. onfinish(loadedFiles);
  17354. }
  17355. };
  17356. var onerror = function (request, exception) {
  17357. if (onErrorCallBack && request) {
  17358. onErrorCallBack(request.status + " " + request.statusText, exception);
  17359. }
  17360. };
  17361. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17362. };
  17363. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17364. if (onError === void 0) { onError = null; }
  17365. var loadedFiles = [];
  17366. loadedFiles._internalCount = 0;
  17367. for (var index = 0; index < 6; index++) {
  17368. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17369. }
  17370. };
  17371. // Statics
  17372. /**
  17373. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17374. * @returns true if the engine can be created
  17375. * @ignorenaming
  17376. */
  17377. Engine.isSupported = function () {
  17378. try {
  17379. var tempcanvas = document.createElement("canvas");
  17380. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17381. return gl != null && !!window.WebGLRenderingContext;
  17382. }
  17383. catch (e) {
  17384. return false;
  17385. }
  17386. };
  17387. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17388. Engine.ExceptionList = [
  17389. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17390. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17391. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17392. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17393. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17394. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17395. ];
  17396. /** Gets the list of created engines */
  17397. Engine.Instances = new Array();
  17398. // Const statics
  17399. Engine._ALPHA_DISABLE = 0;
  17400. Engine._ALPHA_ADD = 1;
  17401. Engine._ALPHA_COMBINE = 2;
  17402. Engine._ALPHA_SUBTRACT = 3;
  17403. Engine._ALPHA_MULTIPLY = 4;
  17404. Engine._ALPHA_MAXIMIZED = 5;
  17405. Engine._ALPHA_ONEONE = 6;
  17406. Engine._ALPHA_PREMULTIPLIED = 7;
  17407. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17408. Engine._ALPHA_INTERPOLATE = 9;
  17409. Engine._ALPHA_SCREENMODE = 10;
  17410. Engine._DELAYLOADSTATE_NONE = 0;
  17411. Engine._DELAYLOADSTATE_LOADED = 1;
  17412. Engine._DELAYLOADSTATE_LOADING = 2;
  17413. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17414. Engine._TEXTUREFORMAT_ALPHA = 0;
  17415. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17416. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17417. Engine._TEXTUREFORMAT_RGB = 4;
  17418. Engine._TEXTUREFORMAT_RGBA = 5;
  17419. Engine._TEXTUREFORMAT_R32F = 6;
  17420. Engine._TEXTUREFORMAT_RG32F = 7;
  17421. Engine._TEXTUREFORMAT_RGB32F = 8;
  17422. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17423. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17424. Engine._TEXTURETYPE_FLOAT = 1;
  17425. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17426. // Depht or Stencil test Constants.
  17427. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17428. 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.
  17429. 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.
  17430. 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.
  17431. 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.
  17432. 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.
  17433. 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.
  17434. 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.
  17435. // Stencil Actions Constants.
  17436. Engine._KEEP = 0x1E00;
  17437. Engine._REPLACE = 0x1E01;
  17438. Engine._INCR = 0x1E02;
  17439. Engine._DECR = 0x1E03;
  17440. Engine._INVERT = 0x150A;
  17441. Engine._INCR_WRAP = 0x8507;
  17442. Engine._DECR_WRAP = 0x8508;
  17443. // Texture rescaling mode
  17444. Engine._SCALEMODE_FLOOR = 1;
  17445. Engine._SCALEMODE_NEAREST = 2;
  17446. Engine._SCALEMODE_CEILING = 3;
  17447. // Updatable statics so stick with vars here
  17448. /**
  17449. * Gets or sets the epsilon value used by collision engine
  17450. */
  17451. Engine.CollisionsEpsilon = 0.001;
  17452. /**
  17453. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17454. */
  17455. Engine.CodeRepository = "src/";
  17456. /**
  17457. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17458. */
  17459. Engine.ShadersRepository = "src/Shaders/";
  17460. return Engine;
  17461. }());
  17462. BABYLON.Engine = Engine;
  17463. })(BABYLON || (BABYLON = {}));
  17464. //# sourceMappingURL=babylon.engine.js.map
  17465. var BABYLON;
  17466. (function (BABYLON) {
  17467. /**
  17468. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17469. */
  17470. var Node = /** @class */ (function () {
  17471. /**
  17472. * Creates a new Node
  17473. * @param {string} name - the name and id to be given to this node
  17474. * @param {BABYLON.Scene} the scene this node will be added to
  17475. */
  17476. function Node(name, scene) {
  17477. if (scene === void 0) { scene = null; }
  17478. /**
  17479. * Gets or sets a string used to store user defined state for the node
  17480. */
  17481. this.state = "";
  17482. /**
  17483. * Gets or sets an object used to store user defined information for the node
  17484. */
  17485. this.metadata = null;
  17486. /**
  17487. * Gets or sets a boolean used to define if the node must be serialized
  17488. */
  17489. this.doNotSerialize = false;
  17490. /** @hidden */
  17491. this._isDisposed = false;
  17492. /**
  17493. * Gets a list of Animations associated with the node
  17494. */
  17495. this.animations = new Array();
  17496. this._ranges = {};
  17497. this._isEnabled = true;
  17498. this._isReady = true;
  17499. /** @hidden */
  17500. this._currentRenderId = -1;
  17501. this._parentRenderId = -1;
  17502. this._childRenderId = -1;
  17503. this._animationPropertiesOverride = null;
  17504. /**
  17505. * An event triggered when the mesh is disposed
  17506. */
  17507. this.onDisposeObservable = new BABYLON.Observable();
  17508. // Behaviors
  17509. this._behaviors = new Array();
  17510. this.name = name;
  17511. this.id = name;
  17512. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17513. this.uniqueId = this._scene.getUniqueId();
  17514. this._initCache();
  17515. }
  17516. /**
  17517. * Gets a boolean indicating if the node has been disposed
  17518. * @returns true if the node was disposed
  17519. */
  17520. Node.prototype.isDisposed = function () {
  17521. return this._isDisposed;
  17522. };
  17523. Object.defineProperty(Node.prototype, "parent", {
  17524. get: function () {
  17525. return this._parentNode;
  17526. },
  17527. /**
  17528. * Gets or sets the parent of the node
  17529. */
  17530. set: function (parent) {
  17531. if (this._parentNode === parent) {
  17532. return;
  17533. }
  17534. // Remove self from list of children of parent
  17535. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17536. var index = this._parentNode._children.indexOf(this);
  17537. if (index !== -1) {
  17538. this._parentNode._children.splice(index, 1);
  17539. }
  17540. }
  17541. // Store new parent
  17542. this._parentNode = parent;
  17543. // Add as child to new parent
  17544. if (this._parentNode) {
  17545. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17546. this._parentNode._children = new Array();
  17547. }
  17548. this._parentNode._children.push(this);
  17549. }
  17550. },
  17551. enumerable: true,
  17552. configurable: true
  17553. });
  17554. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17555. /**
  17556. * Gets or sets the animation properties override
  17557. */
  17558. get: function () {
  17559. if (!this._animationPropertiesOverride) {
  17560. return this._scene.animationPropertiesOverride;
  17561. }
  17562. return this._animationPropertiesOverride;
  17563. },
  17564. set: function (value) {
  17565. this._animationPropertiesOverride = value;
  17566. },
  17567. enumerable: true,
  17568. configurable: true
  17569. });
  17570. /**
  17571. * Gets a string idenfifying the name of the class
  17572. * @returns "Node" string
  17573. */
  17574. Node.prototype.getClassName = function () {
  17575. return "Node";
  17576. };
  17577. Object.defineProperty(Node.prototype, "onDispose", {
  17578. /**
  17579. * Sets a callback that will be raised when the node will be disposed
  17580. */
  17581. set: function (callback) {
  17582. if (this._onDisposeObserver) {
  17583. this.onDisposeObservable.remove(this._onDisposeObserver);
  17584. }
  17585. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17586. },
  17587. enumerable: true,
  17588. configurable: true
  17589. });
  17590. /**
  17591. * Gets the scene of the node
  17592. * @returns a {BABYLON.Scene}
  17593. */
  17594. Node.prototype.getScene = function () {
  17595. return this._scene;
  17596. };
  17597. /**
  17598. * Gets the engine of the node
  17599. * @returns a {BABYLON.Engine}
  17600. */
  17601. Node.prototype.getEngine = function () {
  17602. return this._scene.getEngine();
  17603. };
  17604. /**
  17605. * Attach a behavior to the node
  17606. * @see http://doc.babylonjs.com/features/behaviour
  17607. * @param behavior defines the behavior to attach
  17608. * @returns the current Node
  17609. */
  17610. Node.prototype.addBehavior = function (behavior) {
  17611. var _this = this;
  17612. var index = this._behaviors.indexOf(behavior);
  17613. if (index !== -1) {
  17614. return this;
  17615. }
  17616. behavior.init();
  17617. if (this._scene.isLoading) {
  17618. // We defer the attach when the scene will be loaded
  17619. this._scene.onDataLoadedObservable.addOnce(function () {
  17620. behavior.attach(_this);
  17621. });
  17622. }
  17623. else {
  17624. behavior.attach(this);
  17625. }
  17626. this._behaviors.push(behavior);
  17627. return this;
  17628. };
  17629. /**
  17630. * Remove an attached behavior
  17631. * @see http://doc.babylonjs.com/features/behaviour
  17632. * @param behavior defines the behavior to attach
  17633. * @returns the current Node
  17634. */
  17635. Node.prototype.removeBehavior = function (behavior) {
  17636. var index = this._behaviors.indexOf(behavior);
  17637. if (index === -1) {
  17638. return this;
  17639. }
  17640. this._behaviors[index].detach();
  17641. this._behaviors.splice(index, 1);
  17642. return this;
  17643. };
  17644. Object.defineProperty(Node.prototype, "behaviors", {
  17645. /**
  17646. * Gets the list of attached behaviors
  17647. * @see http://doc.babylonjs.com/features/behaviour
  17648. */
  17649. get: function () {
  17650. return this._behaviors;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. /**
  17656. * Gets an attached behavior by name
  17657. * @param name defines the name of the behavior to look for
  17658. * @see http://doc.babylonjs.com/features/behaviour
  17659. * @returns null if behavior was not found else the requested behavior
  17660. */
  17661. Node.prototype.getBehaviorByName = function (name) {
  17662. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17663. var behavior = _a[_i];
  17664. if (behavior.name === name) {
  17665. return behavior;
  17666. }
  17667. }
  17668. return null;
  17669. };
  17670. /**
  17671. * Returns the world matrix of the node
  17672. * @returns a matrix containing the node's world matrix
  17673. */
  17674. Node.prototype.getWorldMatrix = function () {
  17675. return BABYLON.Matrix.Identity();
  17676. };
  17677. /** @hidden */
  17678. Node.prototype._getWorldMatrixDeterminant = function () {
  17679. return 1;
  17680. };
  17681. // override it in derived class if you add new variables to the cache
  17682. // and call the parent class method
  17683. /** @hidden */
  17684. Node.prototype._initCache = function () {
  17685. this._cache = {};
  17686. this._cache.parent = undefined;
  17687. };
  17688. /** @hidden */
  17689. Node.prototype.updateCache = function (force) {
  17690. if (!force && this.isSynchronized())
  17691. return;
  17692. this._cache.parent = this.parent;
  17693. this._updateCache();
  17694. };
  17695. // override it in derived class if you add new variables to the cache
  17696. // and call the parent class method if !ignoreParentClass
  17697. /** @hidden */
  17698. Node.prototype._updateCache = function (ignoreParentClass) {
  17699. };
  17700. // override it in derived class if you add new variables to the cache
  17701. /** @hidden */
  17702. Node.prototype._isSynchronized = function () {
  17703. return true;
  17704. };
  17705. /** @hidden */
  17706. Node.prototype._markSyncedWithParent = function () {
  17707. if (this.parent) {
  17708. this._parentRenderId = this.parent._childRenderId;
  17709. }
  17710. };
  17711. /** @hidden */
  17712. Node.prototype.isSynchronizedWithParent = function () {
  17713. if (!this.parent) {
  17714. return true;
  17715. }
  17716. if (this._parentRenderId !== this.parent._childRenderId) {
  17717. return false;
  17718. }
  17719. return this.parent.isSynchronized();
  17720. };
  17721. /** @hidden */
  17722. Node.prototype.isSynchronized = function (updateCache) {
  17723. var check = this.hasNewParent();
  17724. check = check || !this.isSynchronizedWithParent();
  17725. check = check || !this._isSynchronized();
  17726. if (updateCache)
  17727. this.updateCache(true);
  17728. return !check;
  17729. };
  17730. /** @hidden */
  17731. Node.prototype.hasNewParent = function (update) {
  17732. if (this._cache.parent === this.parent)
  17733. return false;
  17734. if (update)
  17735. this._cache.parent = this.parent;
  17736. return true;
  17737. };
  17738. /**
  17739. * Is this node ready to be used/rendered
  17740. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17741. * @return true if the node is ready
  17742. */
  17743. Node.prototype.isReady = function (completeCheck) {
  17744. if (completeCheck === void 0) { completeCheck = false; }
  17745. return this._isReady;
  17746. };
  17747. /**
  17748. * Is this node enabled?
  17749. * 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
  17750. * @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
  17751. * @return whether this node (and its parent) is enabled
  17752. */
  17753. Node.prototype.isEnabled = function (checkAncestors) {
  17754. if (checkAncestors === void 0) { checkAncestors = true; }
  17755. if (checkAncestors === false) {
  17756. return this._isEnabled;
  17757. }
  17758. if (this._isEnabled === false) {
  17759. return false;
  17760. }
  17761. if (this.parent !== undefined && this.parent !== null) {
  17762. return this.parent.isEnabled(checkAncestors);
  17763. }
  17764. return true;
  17765. };
  17766. /**
  17767. * Set the enabled state of this node
  17768. * @param value defines the new enabled state
  17769. */
  17770. Node.prototype.setEnabled = function (value) {
  17771. this._isEnabled = value;
  17772. };
  17773. /**
  17774. * Is this node a descendant of the given node?
  17775. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17776. * @param ancestor defines the parent node to inspect
  17777. * @returns a boolean indicating if this node is a descendant of the given node
  17778. */
  17779. Node.prototype.isDescendantOf = function (ancestor) {
  17780. if (this.parent) {
  17781. if (this.parent === ancestor) {
  17782. return true;
  17783. }
  17784. return this.parent.isDescendantOf(ancestor);
  17785. }
  17786. return false;
  17787. };
  17788. /** @hidden */
  17789. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17790. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17791. if (!this._children) {
  17792. return;
  17793. }
  17794. for (var index = 0; index < this._children.length; index++) {
  17795. var item = this._children[index];
  17796. if (!predicate || predicate(item)) {
  17797. results.push(item);
  17798. }
  17799. if (!directDescendantsOnly) {
  17800. item._getDescendants(results, false, predicate);
  17801. }
  17802. }
  17803. };
  17804. /**
  17805. * Will return all nodes that have this node as ascendant
  17806. * @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
  17807. * @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
  17808. * @return all children nodes of all types
  17809. */
  17810. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17811. var results = new Array();
  17812. this._getDescendants(results, directDescendantsOnly, predicate);
  17813. return results;
  17814. };
  17815. /**
  17816. * Get all child-meshes of this node
  17817. * @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
  17818. * @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
  17819. * @returns an array of {BABYLON.AbstractMesh}
  17820. */
  17821. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17822. var results = [];
  17823. this._getDescendants(results, directDescendantsOnly, function (node) {
  17824. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17825. });
  17826. return results;
  17827. };
  17828. /**
  17829. * Get all child-transformNodes of this node
  17830. * @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
  17831. * @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
  17832. * @returns an array of {BABYLON.TransformNode}
  17833. */
  17834. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17835. var results = [];
  17836. this._getDescendants(results, directDescendantsOnly, function (node) {
  17837. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17838. });
  17839. return results;
  17840. };
  17841. /**
  17842. * Get all direct children of this node
  17843. * @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
  17844. * @returns an array of {BABYLON.Node}
  17845. */
  17846. Node.prototype.getChildren = function (predicate) {
  17847. return this.getDescendants(true, predicate);
  17848. };
  17849. /** @hidden */
  17850. Node.prototype._setReady = function (state) {
  17851. if (state === this._isReady) {
  17852. return;
  17853. }
  17854. if (!state) {
  17855. this._isReady = false;
  17856. return;
  17857. }
  17858. if (this.onReady) {
  17859. this.onReady(this);
  17860. }
  17861. this._isReady = true;
  17862. };
  17863. /**
  17864. * Get an animation by name
  17865. * @param name defines the name of the animation to look for
  17866. * @returns null if not found else the requested animation
  17867. */
  17868. Node.prototype.getAnimationByName = function (name) {
  17869. for (var i = 0; i < this.animations.length; i++) {
  17870. var animation = this.animations[i];
  17871. if (animation.name === name) {
  17872. return animation;
  17873. }
  17874. }
  17875. return null;
  17876. };
  17877. /**
  17878. * Creates an animation range for this node
  17879. * @param name defines the name of the range
  17880. * @param from defines the starting key
  17881. * @param to defines the end key
  17882. */
  17883. Node.prototype.createAnimationRange = function (name, from, to) {
  17884. // check name not already in use
  17885. if (!this._ranges[name]) {
  17886. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17887. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17888. if (this.animations[i]) {
  17889. this.animations[i].createRange(name, from, to);
  17890. }
  17891. }
  17892. }
  17893. };
  17894. /**
  17895. * Delete a specific animation range
  17896. * @param name defines the name of the range to delete
  17897. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17898. */
  17899. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17900. if (deleteFrames === void 0) { deleteFrames = true; }
  17901. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17902. if (this.animations[i]) {
  17903. this.animations[i].deleteRange(name, deleteFrames);
  17904. }
  17905. }
  17906. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17907. };
  17908. /**
  17909. * Get an animation range by name
  17910. * @param name defines the name of the animation range to look for
  17911. * @returns null if not found else the requested animation range
  17912. */
  17913. Node.prototype.getAnimationRange = function (name) {
  17914. return this._ranges[name];
  17915. };
  17916. /**
  17917. * Will start the animation sequence
  17918. * @param name defines the range frames for animation sequence
  17919. * @param loop defines if the animation should loop (false by default)
  17920. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17921. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17922. * @returns the object created for this animation. If range does not exist, it will return null
  17923. */
  17924. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17925. var range = this.getAnimationRange(name);
  17926. if (!range) {
  17927. return null;
  17928. }
  17929. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17930. };
  17931. /**
  17932. * Serialize animation ranges into a JSON compatible object
  17933. * @returns serialization object
  17934. */
  17935. Node.prototype.serializeAnimationRanges = function () {
  17936. var serializationRanges = [];
  17937. for (var name in this._ranges) {
  17938. var localRange = this._ranges[name];
  17939. if (!localRange) {
  17940. continue;
  17941. }
  17942. var range = {};
  17943. range.name = name;
  17944. range.from = localRange.from;
  17945. range.to = localRange.to;
  17946. serializationRanges.push(range);
  17947. }
  17948. return serializationRanges;
  17949. };
  17950. /**
  17951. * Computes the world matrix of the node
  17952. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17953. * @returns the world matrix
  17954. */
  17955. Node.prototype.computeWorldMatrix = function (force) {
  17956. return BABYLON.Matrix.Identity();
  17957. };
  17958. /**
  17959. * Releases resources associated with this node.
  17960. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17961. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17962. */
  17963. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17964. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17965. if (!doNotRecurse) {
  17966. var nodes = this.getDescendants(true);
  17967. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17968. var node = nodes_1[_i];
  17969. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17970. }
  17971. }
  17972. else {
  17973. var transformNodes = this.getChildTransformNodes(true);
  17974. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17975. var transformNode = transformNodes_1[_a];
  17976. transformNode.parent = null;
  17977. transformNode.computeWorldMatrix(true);
  17978. }
  17979. }
  17980. this.parent = null;
  17981. // Callback
  17982. this.onDisposeObservable.notifyObservers(this);
  17983. this.onDisposeObservable.clear();
  17984. // Behaviors
  17985. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17986. var behavior = _c[_b];
  17987. behavior.detach();
  17988. }
  17989. this._behaviors = [];
  17990. this._isDisposed = true;
  17991. };
  17992. /**
  17993. * Parse animation range data from a serialization object and store them into a given node
  17994. * @param node defines where to store the animation ranges
  17995. * @param parsedNode defines the serialization object to read data from
  17996. * @param scene defines the hosting scene
  17997. */
  17998. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17999. if (parsedNode.ranges) {
  18000. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18001. var data = parsedNode.ranges[index];
  18002. node.createAnimationRange(data.name, data.from, data.to);
  18003. }
  18004. }
  18005. };
  18006. __decorate([
  18007. BABYLON.serialize()
  18008. ], Node.prototype, "name", void 0);
  18009. __decorate([
  18010. BABYLON.serialize()
  18011. ], Node.prototype, "id", void 0);
  18012. __decorate([
  18013. BABYLON.serialize()
  18014. ], Node.prototype, "uniqueId", void 0);
  18015. __decorate([
  18016. BABYLON.serialize()
  18017. ], Node.prototype, "state", void 0);
  18018. __decorate([
  18019. BABYLON.serialize()
  18020. ], Node.prototype, "metadata", void 0);
  18021. return Node;
  18022. }());
  18023. BABYLON.Node = Node;
  18024. })(BABYLON || (BABYLON = {}));
  18025. //# sourceMappingURL=babylon.node.js.map
  18026. var BABYLON;
  18027. (function (BABYLON) {
  18028. var BoundingSphere = /** @class */ (function () {
  18029. /**
  18030. * Creates a new bounding sphere
  18031. * @param min defines the minimum vector (in local space)
  18032. * @param max defines the maximum vector (in local space)
  18033. */
  18034. function BoundingSphere(min, max) {
  18035. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18036. this.reConstruct(min, max);
  18037. }
  18038. /**
  18039. * Recreates the entire bounding sphere from scratch
  18040. * @param min defines the new minimum vector (in local space)
  18041. * @param max defines the new maximum vector (in local space)
  18042. */
  18043. BoundingSphere.prototype.reConstruct = function (min, max) {
  18044. this.minimum = min.clone();
  18045. this.maximum = max.clone();
  18046. var distance = BABYLON.Vector3.Distance(min, max);
  18047. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18048. this.radius = distance * 0.5;
  18049. this.centerWorld = BABYLON.Vector3.Zero();
  18050. this._update(BABYLON.Matrix.Identity());
  18051. };
  18052. // Methods
  18053. BoundingSphere.prototype._update = function (world) {
  18054. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18055. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18056. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18057. };
  18058. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18059. for (var i = 0; i < 6; i++) {
  18060. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18061. return false;
  18062. }
  18063. return true;
  18064. };
  18065. BoundingSphere.prototype.intersectsPoint = function (point) {
  18066. var x = this.centerWorld.x - point.x;
  18067. var y = this.centerWorld.y - point.y;
  18068. var z = this.centerWorld.z - point.z;
  18069. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18070. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18071. return false;
  18072. return true;
  18073. };
  18074. // Statics
  18075. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18076. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18077. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18078. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18079. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18080. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18081. return false;
  18082. return true;
  18083. };
  18084. return BoundingSphere;
  18085. }());
  18086. BABYLON.BoundingSphere = BoundingSphere;
  18087. })(BABYLON || (BABYLON = {}));
  18088. //# sourceMappingURL=babylon.boundingSphere.js.map
  18089. var BABYLON;
  18090. (function (BABYLON) {
  18091. var BoundingBox = /** @class */ (function () {
  18092. /**
  18093. * Creates a new bounding box
  18094. * @param min defines the minimum vector (in local space)
  18095. * @param max defines the maximum vector (in local space)
  18096. */
  18097. function BoundingBox(min, max) {
  18098. this.vectorsWorld = new Array();
  18099. this.reConstruct(min, max);
  18100. }
  18101. // Methods
  18102. /**
  18103. * Recreates the entire bounding box from scratch
  18104. * @param min defines the new minimum vector (in local space)
  18105. * @param max defines the new maximum vector (in local space)
  18106. */
  18107. BoundingBox.prototype.reConstruct = function (min, max) {
  18108. this.minimum = min.clone();
  18109. this.maximum = max.clone();
  18110. // Bounding vectors
  18111. this.vectors = new Array();
  18112. this.vectors.push(this.minimum.clone());
  18113. this.vectors.push(this.maximum.clone());
  18114. this.vectors.push(this.minimum.clone());
  18115. this.vectors[2].x = this.maximum.x;
  18116. this.vectors.push(this.minimum.clone());
  18117. this.vectors[3].y = this.maximum.y;
  18118. this.vectors.push(this.minimum.clone());
  18119. this.vectors[4].z = this.maximum.z;
  18120. this.vectors.push(this.maximum.clone());
  18121. this.vectors[5].z = this.minimum.z;
  18122. this.vectors.push(this.maximum.clone());
  18123. this.vectors[6].x = this.minimum.x;
  18124. this.vectors.push(this.maximum.clone());
  18125. this.vectors[7].y = this.minimum.y;
  18126. // OBB
  18127. this.center = this.maximum.add(this.minimum).scale(0.5);
  18128. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18129. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18130. // World
  18131. for (var index = 0; index < this.vectors.length; index++) {
  18132. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18133. }
  18134. this.minimumWorld = BABYLON.Vector3.Zero();
  18135. this.maximumWorld = BABYLON.Vector3.Zero();
  18136. this.centerWorld = BABYLON.Vector3.Zero();
  18137. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18138. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18139. };
  18140. BoundingBox.prototype.getWorldMatrix = function () {
  18141. return this._worldMatrix;
  18142. };
  18143. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18144. this._worldMatrix.copyFrom(matrix);
  18145. return this;
  18146. };
  18147. BoundingBox.prototype._update = function (world) {
  18148. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18149. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18150. for (var index = 0; index < this.vectors.length; index++) {
  18151. var v = this.vectorsWorld[index];
  18152. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18153. if (v.x < this.minimumWorld.x)
  18154. this.minimumWorld.x = v.x;
  18155. if (v.y < this.minimumWorld.y)
  18156. this.minimumWorld.y = v.y;
  18157. if (v.z < this.minimumWorld.z)
  18158. this.minimumWorld.z = v.z;
  18159. if (v.x > this.maximumWorld.x)
  18160. this.maximumWorld.x = v.x;
  18161. if (v.y > this.maximumWorld.y)
  18162. this.maximumWorld.y = v.y;
  18163. if (v.z > this.maximumWorld.z)
  18164. this.maximumWorld.z = v.z;
  18165. }
  18166. // Extend
  18167. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18168. this.extendSizeWorld.scaleInPlace(0.5);
  18169. // OBB
  18170. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18171. this.centerWorld.scaleInPlace(0.5);
  18172. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18173. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18174. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18175. this._worldMatrix = world;
  18176. };
  18177. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18178. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18179. };
  18180. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18181. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18182. };
  18183. BoundingBox.prototype.intersectsPoint = function (point) {
  18184. var delta = -BABYLON.Epsilon;
  18185. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18186. return false;
  18187. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18188. return false;
  18189. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18190. return false;
  18191. return true;
  18192. };
  18193. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18194. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18195. };
  18196. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18197. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18198. return false;
  18199. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18200. return false;
  18201. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18202. return false;
  18203. return true;
  18204. };
  18205. // Statics
  18206. BoundingBox.Intersects = function (box0, box1) {
  18207. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18208. return false;
  18209. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18210. return false;
  18211. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18212. return false;
  18213. return true;
  18214. };
  18215. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18216. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18217. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18218. return (num <= (sphereRadius * sphereRadius));
  18219. };
  18220. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18221. for (var p = 0; p < 6; p++) {
  18222. for (var i = 0; i < 8; i++) {
  18223. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18224. return false;
  18225. }
  18226. }
  18227. }
  18228. return true;
  18229. };
  18230. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18231. for (var p = 0; p < 6; p++) {
  18232. var inCount = 8;
  18233. for (var i = 0; i < 8; i++) {
  18234. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18235. --inCount;
  18236. }
  18237. else {
  18238. break;
  18239. }
  18240. }
  18241. if (inCount === 0)
  18242. return false;
  18243. }
  18244. return true;
  18245. };
  18246. return BoundingBox;
  18247. }());
  18248. BABYLON.BoundingBox = BoundingBox;
  18249. })(BABYLON || (BABYLON = {}));
  18250. //# sourceMappingURL=babylon.boundingBox.js.map
  18251. var BABYLON;
  18252. (function (BABYLON) {
  18253. var computeBoxExtents = function (axis, box) {
  18254. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18255. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18256. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18257. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18258. var r = r0 + r1 + r2;
  18259. return {
  18260. min: p - r,
  18261. max: p + r
  18262. };
  18263. };
  18264. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18265. var axisOverlap = function (axis, box0, box1) {
  18266. var result0 = computeBoxExtents(axis, box0);
  18267. var result1 = computeBoxExtents(axis, box1);
  18268. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18269. };
  18270. var BoundingInfo = /** @class */ (function () {
  18271. function BoundingInfo(minimum, maximum) {
  18272. this.minimum = minimum;
  18273. this.maximum = maximum;
  18274. this._isLocked = false;
  18275. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18276. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18277. }
  18278. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18279. get: function () {
  18280. return this._isLocked;
  18281. },
  18282. set: function (value) {
  18283. this._isLocked = value;
  18284. },
  18285. enumerable: true,
  18286. configurable: true
  18287. });
  18288. // Methods
  18289. BoundingInfo.prototype.update = function (world) {
  18290. if (this._isLocked) {
  18291. return;
  18292. }
  18293. this.boundingBox._update(world);
  18294. this.boundingSphere._update(world);
  18295. };
  18296. /**
  18297. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18298. * @param center New center of the bounding info
  18299. * @param extend New extend of the bounding info
  18300. */
  18301. BoundingInfo.prototype.centerOn = function (center, extend) {
  18302. this.minimum = center.subtract(extend);
  18303. this.maximum = center.add(extend);
  18304. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18305. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18306. return this;
  18307. };
  18308. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18309. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18310. return false;
  18311. return this.boundingBox.isInFrustum(frustumPlanes);
  18312. };
  18313. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18314. /**
  18315. * Gets the world distance between the min and max points of the bounding box
  18316. */
  18317. get: function () {
  18318. var boundingBox = this.boundingBox;
  18319. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18320. return size.length();
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18326. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18327. };
  18328. BoundingInfo.prototype._checkCollision = function (collider) {
  18329. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18330. };
  18331. BoundingInfo.prototype.intersectsPoint = function (point) {
  18332. if (!this.boundingSphere.centerWorld) {
  18333. return false;
  18334. }
  18335. if (!this.boundingSphere.intersectsPoint(point)) {
  18336. return false;
  18337. }
  18338. if (!this.boundingBox.intersectsPoint(point)) {
  18339. return false;
  18340. }
  18341. return true;
  18342. };
  18343. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18344. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18345. return false;
  18346. }
  18347. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18348. return false;
  18349. }
  18350. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18351. return false;
  18352. }
  18353. if (!precise) {
  18354. return true;
  18355. }
  18356. var box0 = this.boundingBox;
  18357. var box1 = boundingInfo.boundingBox;
  18358. if (!axisOverlap(box0.directions[0], box0, box1))
  18359. return false;
  18360. if (!axisOverlap(box0.directions[1], box0, box1))
  18361. return false;
  18362. if (!axisOverlap(box0.directions[2], box0, box1))
  18363. return false;
  18364. if (!axisOverlap(box1.directions[0], box0, box1))
  18365. return false;
  18366. if (!axisOverlap(box1.directions[1], box0, box1))
  18367. return false;
  18368. if (!axisOverlap(box1.directions[2], box0, box1))
  18369. return false;
  18370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18371. return false;
  18372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18373. return false;
  18374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18375. return false;
  18376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18377. return false;
  18378. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18379. return false;
  18380. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18381. return false;
  18382. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18383. return false;
  18384. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18385. return false;
  18386. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18387. return false;
  18388. return true;
  18389. };
  18390. return BoundingInfo;
  18391. }());
  18392. BABYLON.BoundingInfo = BoundingInfo;
  18393. })(BABYLON || (BABYLON = {}));
  18394. //# sourceMappingURL=babylon.boundingInfo.js.map
  18395. var BABYLON;
  18396. (function (BABYLON) {
  18397. var TransformNode = /** @class */ (function (_super) {
  18398. __extends(TransformNode, _super);
  18399. function TransformNode(name, scene, isPure) {
  18400. if (scene === void 0) { scene = null; }
  18401. if (isPure === void 0) { isPure = true; }
  18402. var _this = _super.call(this, name, scene) || this;
  18403. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18404. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18405. _this._up = new BABYLON.Vector3(0, 1, 0);
  18406. _this._right = new BABYLON.Vector3(1, 0, 0);
  18407. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18408. // Properties
  18409. _this._rotation = BABYLON.Vector3.Zero();
  18410. _this._scaling = BABYLON.Vector3.One();
  18411. _this._isDirty = false;
  18412. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18413. _this.scalingDeterminant = 1;
  18414. _this.infiniteDistance = false;
  18415. _this.position = BABYLON.Vector3.Zero();
  18416. _this._localWorld = BABYLON.Matrix.Zero();
  18417. _this._worldMatrix = BABYLON.Matrix.Zero();
  18418. _this._worldMatrixDeterminant = 0;
  18419. _this._absolutePosition = BABYLON.Vector3.Zero();
  18420. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18421. _this._postMultiplyPivotMatrix = false;
  18422. _this._isWorldMatrixFrozen = false;
  18423. /**
  18424. * An event triggered after the world matrix is updated
  18425. */
  18426. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18427. _this._nonUniformScaling = false;
  18428. if (isPure) {
  18429. _this.getScene().addTransformNode(_this);
  18430. }
  18431. return _this;
  18432. }
  18433. /**
  18434. * Gets a string idenfifying the name of the class
  18435. * @returns "TransformNode" string
  18436. */
  18437. TransformNode.prototype.getClassName = function () {
  18438. return "TransformNode";
  18439. };
  18440. Object.defineProperty(TransformNode.prototype, "rotation", {
  18441. /**
  18442. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18443. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18444. * Default : (0.0, 0.0, 0.0)
  18445. */
  18446. get: function () {
  18447. return this._rotation;
  18448. },
  18449. set: function (newRotation) {
  18450. this._rotation = newRotation;
  18451. },
  18452. enumerable: true,
  18453. configurable: true
  18454. });
  18455. Object.defineProperty(TransformNode.prototype, "scaling", {
  18456. /**
  18457. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18458. * Default : (1.0, 1.0, 1.0)
  18459. */
  18460. get: function () {
  18461. return this._scaling;
  18462. },
  18463. /**
  18464. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18465. * Default : (1.0, 1.0, 1.0)
  18466. */
  18467. set: function (newScaling) {
  18468. this._scaling = newScaling;
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18474. /**
  18475. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18476. * It's null by default.
  18477. * 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)
  18478. */
  18479. get: function () {
  18480. return this._rotationQuaternion;
  18481. },
  18482. set: function (quaternion) {
  18483. this._rotationQuaternion = quaternion;
  18484. //reset the rotation vector.
  18485. if (quaternion && this.rotation.length()) {
  18486. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18487. }
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. Object.defineProperty(TransformNode.prototype, "forward", {
  18493. /**
  18494. * The forward direction of that transform in world space.
  18495. */
  18496. get: function () {
  18497. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18498. },
  18499. enumerable: true,
  18500. configurable: true
  18501. });
  18502. Object.defineProperty(TransformNode.prototype, "up", {
  18503. /**
  18504. * The up direction of that transform in world space.
  18505. */
  18506. get: function () {
  18507. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18508. },
  18509. enumerable: true,
  18510. configurable: true
  18511. });
  18512. Object.defineProperty(TransformNode.prototype, "right", {
  18513. /**
  18514. * The right direction of that transform in world space.
  18515. */
  18516. get: function () {
  18517. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. /**
  18523. * Returns the latest update of the World matrix
  18524. * Returns a Matrix.
  18525. */
  18526. TransformNode.prototype.getWorldMatrix = function () {
  18527. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18528. this.computeWorldMatrix();
  18529. }
  18530. return this._worldMatrix;
  18531. };
  18532. /** @hidden */
  18533. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18534. return this._worldMatrixDeterminant;
  18535. };
  18536. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18537. /**
  18538. * Returns directly the latest state of the mesh World matrix.
  18539. * A Matrix is returned.
  18540. */
  18541. get: function () {
  18542. return this._worldMatrix;
  18543. },
  18544. enumerable: true,
  18545. configurable: true
  18546. });
  18547. /**
  18548. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18549. * Returns the TransformNode.
  18550. */
  18551. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18552. this._poseMatrix.copyFrom(matrix);
  18553. return this;
  18554. };
  18555. /**
  18556. * Returns the mesh Pose matrix.
  18557. * Returned object : Matrix
  18558. */
  18559. TransformNode.prototype.getPoseMatrix = function () {
  18560. return this._poseMatrix;
  18561. };
  18562. TransformNode.prototype._isSynchronized = function () {
  18563. if (this._isDirty) {
  18564. return false;
  18565. }
  18566. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18567. return false;
  18568. if (this._cache.pivotMatrixUpdated) {
  18569. return false;
  18570. }
  18571. if (this.infiniteDistance) {
  18572. return false;
  18573. }
  18574. if (!this._cache.position.equals(this.position))
  18575. return false;
  18576. if (this.rotationQuaternion) {
  18577. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18578. return false;
  18579. }
  18580. if (!this._cache.rotation.equals(this.rotation))
  18581. return false;
  18582. if (!this._cache.scaling.equals(this.scaling))
  18583. return false;
  18584. return true;
  18585. };
  18586. TransformNode.prototype._initCache = function () {
  18587. _super.prototype._initCache.call(this);
  18588. this._cache.localMatrixUpdated = false;
  18589. this._cache.position = BABYLON.Vector3.Zero();
  18590. this._cache.scaling = BABYLON.Vector3.Zero();
  18591. this._cache.rotation = BABYLON.Vector3.Zero();
  18592. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18593. this._cache.billboardMode = -1;
  18594. };
  18595. TransformNode.prototype.markAsDirty = function (property) {
  18596. if (property === "rotation") {
  18597. this.rotationQuaternion = null;
  18598. }
  18599. this._currentRenderId = Number.MAX_VALUE;
  18600. this._isDirty = true;
  18601. return this;
  18602. };
  18603. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18604. /**
  18605. * Returns the current mesh absolute position.
  18606. * Retuns a Vector3.
  18607. */
  18608. get: function () {
  18609. return this._absolutePosition;
  18610. },
  18611. enumerable: true,
  18612. configurable: true
  18613. });
  18614. /**
  18615. * Sets a new matrix to apply before all other transformation
  18616. * @param matrix defines the transform matrix
  18617. * @returns the current TransformNode
  18618. */
  18619. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18620. return this.setPivotMatrix(matrix, false);
  18621. };
  18622. /**
  18623. * Sets a new pivot matrix to the current node
  18624. * @param matrix defines the new pivot matrix to use
  18625. * @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
  18626. * @returns the current TransformNode
  18627. */
  18628. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18629. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18630. this._pivotMatrix = matrix.clone();
  18631. this._cache.pivotMatrixUpdated = true;
  18632. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18633. if (this._postMultiplyPivotMatrix) {
  18634. if (!this._pivotMatrixInverse) {
  18635. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18636. }
  18637. else {
  18638. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18639. }
  18640. }
  18641. return this;
  18642. };
  18643. /**
  18644. * Returns the mesh pivot matrix.
  18645. * Default : Identity.
  18646. * A Matrix is returned.
  18647. */
  18648. TransformNode.prototype.getPivotMatrix = function () {
  18649. return this._pivotMatrix;
  18650. };
  18651. /**
  18652. * Prevents the World matrix to be computed any longer.
  18653. * Returns the TransformNode.
  18654. */
  18655. TransformNode.prototype.freezeWorldMatrix = function () {
  18656. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18657. this.computeWorldMatrix(true);
  18658. this._isWorldMatrixFrozen = true;
  18659. return this;
  18660. };
  18661. /**
  18662. * Allows back the World matrix computation.
  18663. * Returns the TransformNode.
  18664. */
  18665. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18666. this._isWorldMatrixFrozen = false;
  18667. this.computeWorldMatrix(true);
  18668. return this;
  18669. };
  18670. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18671. /**
  18672. * True if the World matrix has been frozen.
  18673. * Returns a boolean.
  18674. */
  18675. get: function () {
  18676. return this._isWorldMatrixFrozen;
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. /**
  18682. * Retuns the mesh absolute position in the World.
  18683. * Returns a Vector3.
  18684. */
  18685. TransformNode.prototype.getAbsolutePosition = function () {
  18686. this.computeWorldMatrix();
  18687. return this._absolutePosition;
  18688. };
  18689. /**
  18690. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18691. * Returns the TransformNode.
  18692. */
  18693. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18694. if (!absolutePosition) {
  18695. return this;
  18696. }
  18697. var absolutePositionX;
  18698. var absolutePositionY;
  18699. var absolutePositionZ;
  18700. if (absolutePosition.x === undefined) {
  18701. if (arguments.length < 3) {
  18702. return this;
  18703. }
  18704. absolutePositionX = arguments[0];
  18705. absolutePositionY = arguments[1];
  18706. absolutePositionZ = arguments[2];
  18707. }
  18708. else {
  18709. absolutePositionX = absolutePosition.x;
  18710. absolutePositionY = absolutePosition.y;
  18711. absolutePositionZ = absolutePosition.z;
  18712. }
  18713. if (this.parent) {
  18714. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18715. invertParentWorldMatrix.invert();
  18716. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18717. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18718. }
  18719. else {
  18720. this.position.x = absolutePositionX;
  18721. this.position.y = absolutePositionY;
  18722. this.position.z = absolutePositionZ;
  18723. }
  18724. return this;
  18725. };
  18726. /**
  18727. * Sets the mesh position in its local space.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18731. this.computeWorldMatrix();
  18732. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18733. return this;
  18734. };
  18735. /**
  18736. * Returns the mesh position in the local space from the current World matrix values.
  18737. * Returns a new Vector3.
  18738. */
  18739. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18740. this.computeWorldMatrix();
  18741. var invLocalWorldMatrix = this._localWorld.clone();
  18742. invLocalWorldMatrix.invert();
  18743. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18744. };
  18745. /**
  18746. * Translates the mesh along the passed Vector3 in its local space.
  18747. * Returns the TransformNode.
  18748. */
  18749. TransformNode.prototype.locallyTranslate = function (vector3) {
  18750. this.computeWorldMatrix(true);
  18751. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18752. return this;
  18753. };
  18754. /**
  18755. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18756. * @param targetPoint the position (must be in same space as current mesh) to look at
  18757. * @param yawCor optional yaw (y-axis) correction in radians
  18758. * @param pitchCor optional pitch (x-axis) correction in radians
  18759. * @param rollCor optional roll (z-axis) correction in radians
  18760. * @param space the choosen space of the target
  18761. * @returns the TransformNode.
  18762. */
  18763. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18764. if (yawCor === void 0) { yawCor = 0; }
  18765. if (pitchCor === void 0) { pitchCor = 0; }
  18766. if (rollCor === void 0) { rollCor = 0; }
  18767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18768. var dv = TransformNode._lookAtVectorCache;
  18769. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18770. targetPoint.subtractToRef(pos, dv);
  18771. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18772. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18773. var pitch = Math.atan2(dv.y, len);
  18774. if (this.rotationQuaternion) {
  18775. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18776. }
  18777. else {
  18778. this.rotation.x = pitch + pitchCor;
  18779. this.rotation.y = yaw + yawCor;
  18780. this.rotation.z = rollCor;
  18781. }
  18782. return this;
  18783. };
  18784. /**
  18785. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18786. * This Vector3 is expressed in the World space.
  18787. */
  18788. TransformNode.prototype.getDirection = function (localAxis) {
  18789. var result = BABYLON.Vector3.Zero();
  18790. this.getDirectionToRef(localAxis, result);
  18791. return result;
  18792. };
  18793. /**
  18794. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18795. * localAxis is expressed in the mesh local space.
  18796. * result is computed in the Wordl space from the mesh World matrix.
  18797. * Returns the TransformNode.
  18798. */
  18799. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18800. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18801. return this;
  18802. };
  18803. /**
  18804. * Sets a new pivot point to the current node
  18805. * @param point defines the new pivot point to use
  18806. * @param space defines if the point is in world or local space (local by default)
  18807. * @returns the current TransformNode
  18808. */
  18809. TransformNode.prototype.setPivotPoint = function (point, space) {
  18810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18811. if (this.getScene().getRenderId() == 0) {
  18812. this.computeWorldMatrix(true);
  18813. }
  18814. var wm = this.getWorldMatrix();
  18815. if (space == BABYLON.Space.WORLD) {
  18816. var tmat = BABYLON.Tmp.Matrix[0];
  18817. wm.invertToRef(tmat);
  18818. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18819. }
  18820. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18821. };
  18822. /**
  18823. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18824. */
  18825. TransformNode.prototype.getPivotPoint = function () {
  18826. var point = BABYLON.Vector3.Zero();
  18827. this.getPivotPointToRef(point);
  18828. return point;
  18829. };
  18830. /**
  18831. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18832. * Returns the TransformNode.
  18833. */
  18834. TransformNode.prototype.getPivotPointToRef = function (result) {
  18835. result.x = -this._pivotMatrix.m[12];
  18836. result.y = -this._pivotMatrix.m[13];
  18837. result.z = -this._pivotMatrix.m[14];
  18838. return this;
  18839. };
  18840. /**
  18841. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18842. */
  18843. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18844. var point = BABYLON.Vector3.Zero();
  18845. this.getAbsolutePivotPointToRef(point);
  18846. return point;
  18847. };
  18848. /**
  18849. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18850. * Returns the TransformNode.
  18851. */
  18852. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18853. result.x = this._pivotMatrix.m[12];
  18854. result.y = this._pivotMatrix.m[13];
  18855. result.z = this._pivotMatrix.m[14];
  18856. this.getPivotPointToRef(result);
  18857. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18858. return this;
  18859. };
  18860. /**
  18861. * Defines the passed node as the parent of the current node.
  18862. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18863. * Returns the TransformNode.
  18864. */
  18865. TransformNode.prototype.setParent = function (node) {
  18866. if (node === null) {
  18867. var rotation = BABYLON.Tmp.Quaternion[0];
  18868. var position = BABYLON.Tmp.Vector3[0];
  18869. var scale = BABYLON.Tmp.Vector3[1];
  18870. if (this.parent && this.parent.computeWorldMatrix) {
  18871. this.parent.computeWorldMatrix(true);
  18872. }
  18873. this.computeWorldMatrix(true);
  18874. this.getWorldMatrix().decompose(scale, rotation, position);
  18875. if (this.rotationQuaternion) {
  18876. this.rotationQuaternion.copyFrom(rotation);
  18877. }
  18878. else {
  18879. rotation.toEulerAnglesToRef(this.rotation);
  18880. }
  18881. this.scaling.x = scale.x;
  18882. this.scaling.y = scale.y;
  18883. this.scaling.z = scale.z;
  18884. this.position.x = position.x;
  18885. this.position.y = position.y;
  18886. this.position.z = position.z;
  18887. }
  18888. else {
  18889. var rotation = BABYLON.Tmp.Quaternion[0];
  18890. var position = BABYLON.Tmp.Vector3[0];
  18891. var scale = BABYLON.Tmp.Vector3[1];
  18892. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18893. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18894. this.computeWorldMatrix(true);
  18895. node.computeWorldMatrix(true);
  18896. node.getWorldMatrix().invertToRef(invParentMatrix);
  18897. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18898. diffMatrix.decompose(scale, rotation, position);
  18899. if (this.rotationQuaternion) {
  18900. this.rotationQuaternion.copyFrom(rotation);
  18901. }
  18902. else {
  18903. rotation.toEulerAnglesToRef(this.rotation);
  18904. }
  18905. this.position.x = position.x;
  18906. this.position.y = position.y;
  18907. this.position.z = position.z;
  18908. this.scaling.x = scale.x;
  18909. this.scaling.y = scale.y;
  18910. this.scaling.z = scale.z;
  18911. }
  18912. this.parent = node;
  18913. return this;
  18914. };
  18915. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18916. get: function () {
  18917. return this._nonUniformScaling;
  18918. },
  18919. enumerable: true,
  18920. configurable: true
  18921. });
  18922. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18923. if (this._nonUniformScaling === value) {
  18924. return false;
  18925. }
  18926. this._nonUniformScaling = true;
  18927. return true;
  18928. };
  18929. /**
  18930. * Attach the current TransformNode to another TransformNode associated with a bone
  18931. * @param bone Bone affecting the TransformNode
  18932. * @param affectedTransformNode TransformNode associated with the bone
  18933. */
  18934. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18935. this._transformToBoneReferal = affectedTransformNode;
  18936. this.parent = bone;
  18937. if (bone.getWorldMatrix().determinant() < 0) {
  18938. this.scalingDeterminant *= -1;
  18939. }
  18940. return this;
  18941. };
  18942. TransformNode.prototype.detachFromBone = function () {
  18943. if (!this.parent) {
  18944. return this;
  18945. }
  18946. if (this.parent.getWorldMatrix().determinant() < 0) {
  18947. this.scalingDeterminant *= -1;
  18948. }
  18949. this._transformToBoneReferal = null;
  18950. this.parent = null;
  18951. return this;
  18952. };
  18953. /**
  18954. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18955. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18956. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18957. * The passed axis is also normalized.
  18958. * Returns the TransformNode.
  18959. */
  18960. TransformNode.prototype.rotate = function (axis, amount, space) {
  18961. axis.normalize();
  18962. if (!this.rotationQuaternion) {
  18963. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18964. this.rotation = BABYLON.Vector3.Zero();
  18965. }
  18966. var rotationQuaternion;
  18967. if (!space || space === BABYLON.Space.LOCAL) {
  18968. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18969. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18970. }
  18971. else {
  18972. if (this.parent) {
  18973. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18974. invertParentWorldMatrix.invert();
  18975. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18976. }
  18977. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18978. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18979. }
  18980. return this;
  18981. };
  18982. /**
  18983. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18984. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18985. * The passed axis is also normalized.
  18986. * Returns the TransformNode.
  18987. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18988. */
  18989. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18990. axis.normalize();
  18991. if (!this.rotationQuaternion) {
  18992. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18993. this.rotation.copyFromFloats(0, 0, 0);
  18994. }
  18995. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18996. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18997. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18998. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18999. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19000. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19001. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19002. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19003. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19004. return this;
  19005. };
  19006. /**
  19007. * Translates the mesh along the axis vector for the passed distance in the given space.
  19008. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19009. * Returns the TransformNode.
  19010. */
  19011. TransformNode.prototype.translate = function (axis, distance, space) {
  19012. var displacementVector = axis.scale(distance);
  19013. if (!space || space === BABYLON.Space.LOCAL) {
  19014. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19015. this.setPositionWithLocalVector(tempV3);
  19016. }
  19017. else {
  19018. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19019. }
  19020. return this;
  19021. };
  19022. /**
  19023. * Adds a rotation step to the mesh current rotation.
  19024. * x, y, z are Euler angles expressed in radians.
  19025. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19026. * This means this rotation is made in the mesh local space only.
  19027. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19028. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19029. * ```javascript
  19030. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19031. * ```
  19032. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19033. * 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.
  19034. * Returns the TransformNode.
  19035. */
  19036. TransformNode.prototype.addRotation = function (x, y, z) {
  19037. var rotationQuaternion;
  19038. if (this.rotationQuaternion) {
  19039. rotationQuaternion = this.rotationQuaternion;
  19040. }
  19041. else {
  19042. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19043. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19044. }
  19045. var accumulation = BABYLON.Tmp.Quaternion[0];
  19046. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19047. rotationQuaternion.multiplyInPlace(accumulation);
  19048. if (!this.rotationQuaternion) {
  19049. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19050. }
  19051. return this;
  19052. };
  19053. /**
  19054. * Computes the mesh World matrix and returns it.
  19055. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19056. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19057. * If the parameter `force`is set to `true`, the actual computation is done.
  19058. * Returns the mesh World Matrix.
  19059. */
  19060. TransformNode.prototype.computeWorldMatrix = function (force) {
  19061. if (this._isWorldMatrixFrozen) {
  19062. return this._worldMatrix;
  19063. }
  19064. if (!force && this.isSynchronized(true)) {
  19065. this._currentRenderId = this.getScene().getRenderId();
  19066. return this._worldMatrix;
  19067. }
  19068. this._cache.position.copyFrom(this.position);
  19069. this._cache.scaling.copyFrom(this.scaling);
  19070. this._cache.pivotMatrixUpdated = false;
  19071. this._cache.billboardMode = this.billboardMode;
  19072. this._currentRenderId = this.getScene().getRenderId();
  19073. this._childRenderId = this.getScene().getRenderId();
  19074. this._isDirty = false;
  19075. // Scaling
  19076. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19077. // Rotation
  19078. //rotate, if quaternion is set and rotation was used
  19079. if (this.rotationQuaternion) {
  19080. var len = this.rotation.length();
  19081. if (len) {
  19082. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19083. this.rotation.copyFromFloats(0, 0, 0);
  19084. }
  19085. }
  19086. if (this.rotationQuaternion) {
  19087. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19088. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19089. }
  19090. else {
  19091. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19092. this._cache.rotation.copyFrom(this.rotation);
  19093. }
  19094. // Translation
  19095. var camera = this.getScene().activeCamera;
  19096. if (this.infiniteDistance && !this.parent && camera) {
  19097. var cameraWorldMatrix = camera.getWorldMatrix();
  19098. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19099. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19100. }
  19101. else {
  19102. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19103. }
  19104. // Composing transformations
  19105. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19106. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19107. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19108. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19109. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19110. // Need to decompose each rotation here
  19111. var currentPosition = BABYLON.Tmp.Vector3[3];
  19112. if (this.parent && this.parent.getWorldMatrix) {
  19113. if (this._transformToBoneReferal) {
  19114. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19115. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19116. }
  19117. else {
  19118. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19119. }
  19120. }
  19121. else {
  19122. currentPosition.copyFrom(this.position);
  19123. }
  19124. currentPosition.subtractInPlace(camera.globalPosition);
  19125. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19126. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19127. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19128. }
  19129. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19130. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19131. }
  19132. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19133. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19134. }
  19135. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19136. }
  19137. else {
  19138. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19139. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19140. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19141. }
  19142. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19143. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19144. }
  19145. // Local world
  19146. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19147. // Parent
  19148. if (this.parent && this.parent.getWorldMatrix) {
  19149. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19150. if (this._transformToBoneReferal) {
  19151. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19152. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19153. }
  19154. else {
  19155. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19156. }
  19157. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19158. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19159. this._worldMatrix.copyFrom(this._localWorld);
  19160. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19161. }
  19162. else {
  19163. if (this._transformToBoneReferal) {
  19164. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19165. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19166. }
  19167. else {
  19168. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19169. }
  19170. }
  19171. this._markSyncedWithParent();
  19172. }
  19173. else {
  19174. this._worldMatrix.copyFrom(this._localWorld);
  19175. }
  19176. // Post multiply inverse of pivotMatrix
  19177. if (this._postMultiplyPivotMatrix) {
  19178. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19179. }
  19180. // Normal matrix
  19181. if (this.scaling.isNonUniform) {
  19182. this._updateNonUniformScalingState(true);
  19183. }
  19184. else if (this.parent && this.parent._nonUniformScaling) {
  19185. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19186. }
  19187. else {
  19188. this._updateNonUniformScalingState(false);
  19189. }
  19190. this._afterComputeWorldMatrix();
  19191. // Absolute position
  19192. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19193. // Callbacks
  19194. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19195. if (!this._poseMatrix) {
  19196. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19197. }
  19198. // Cache the determinant
  19199. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19200. return this._worldMatrix;
  19201. };
  19202. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19203. };
  19204. /**
  19205. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19206. * @param func: callback function to add
  19207. *
  19208. * Returns the TransformNode.
  19209. */
  19210. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19211. this.onAfterWorldMatrixUpdateObservable.add(func);
  19212. return this;
  19213. };
  19214. /**
  19215. * Removes a registered callback function.
  19216. * Returns the TransformNode.
  19217. */
  19218. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19219. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19220. return this;
  19221. };
  19222. /**
  19223. * Clone the current transform node
  19224. * Returns the new transform node
  19225. * @param name Name of the new clone
  19226. * @param newParent New parent for the clone
  19227. * @param doNotCloneChildren Do not clone children hierarchy
  19228. */
  19229. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19230. var _this = this;
  19231. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19232. result.name = name;
  19233. result.id = name;
  19234. if (newParent) {
  19235. result.parent = newParent;
  19236. }
  19237. if (!doNotCloneChildren) {
  19238. // Children
  19239. var directDescendants = this.getDescendants(true);
  19240. for (var index = 0; index < directDescendants.length; index++) {
  19241. var child = directDescendants[index];
  19242. if (child.clone) {
  19243. child.clone(name + "." + child.name, result);
  19244. }
  19245. }
  19246. }
  19247. return result;
  19248. };
  19249. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19250. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19251. serializationObject.type = this.getClassName();
  19252. // Parent
  19253. if (this.parent) {
  19254. serializationObject.parentId = this.parent.id;
  19255. }
  19256. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19257. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19258. }
  19259. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19260. serializationObject.isEnabled = this.isEnabled();
  19261. // Parent
  19262. if (this.parent) {
  19263. serializationObject.parentId = this.parent.id;
  19264. }
  19265. return serializationObject;
  19266. };
  19267. // Statics
  19268. /**
  19269. * Returns a new TransformNode object parsed from the source provided.
  19270. * The parameter `parsedMesh` is the source.
  19271. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19272. */
  19273. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19274. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19275. if (BABYLON.Tags) {
  19276. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19277. }
  19278. if (parsedTransformNode.localMatrix) {
  19279. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19280. }
  19281. else if (parsedTransformNode.pivotMatrix) {
  19282. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19283. }
  19284. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19285. // Parent
  19286. if (parsedTransformNode.parentId) {
  19287. transformNode._waitingParentId = parsedTransformNode.parentId;
  19288. }
  19289. return transformNode;
  19290. };
  19291. /**
  19292. * Releases resources associated with this transform node.
  19293. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19294. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19295. */
  19296. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19297. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19298. // Animations
  19299. this.getScene().stopAnimation(this);
  19300. // Remove from scene
  19301. this.getScene().removeTransformNode(this);
  19302. this.onAfterWorldMatrixUpdateObservable.clear();
  19303. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19304. };
  19305. // Statics
  19306. TransformNode.BILLBOARDMODE_NONE = 0;
  19307. TransformNode.BILLBOARDMODE_X = 1;
  19308. TransformNode.BILLBOARDMODE_Y = 2;
  19309. TransformNode.BILLBOARDMODE_Z = 4;
  19310. TransformNode.BILLBOARDMODE_ALL = 7;
  19311. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19312. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19313. __decorate([
  19314. BABYLON.serializeAsVector3()
  19315. ], TransformNode.prototype, "_rotation", void 0);
  19316. __decorate([
  19317. BABYLON.serializeAsQuaternion()
  19318. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19319. __decorate([
  19320. BABYLON.serializeAsVector3()
  19321. ], TransformNode.prototype, "_scaling", void 0);
  19322. __decorate([
  19323. BABYLON.serialize()
  19324. ], TransformNode.prototype, "billboardMode", void 0);
  19325. __decorate([
  19326. BABYLON.serialize()
  19327. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19328. __decorate([
  19329. BABYLON.serialize()
  19330. ], TransformNode.prototype, "infiniteDistance", void 0);
  19331. __decorate([
  19332. BABYLON.serializeAsVector3()
  19333. ], TransformNode.prototype, "position", void 0);
  19334. return TransformNode;
  19335. }(BABYLON.Node));
  19336. BABYLON.TransformNode = TransformNode;
  19337. })(BABYLON || (BABYLON = {}));
  19338. //# sourceMappingURL=babylon.transformNode.js.map
  19339. var BABYLON;
  19340. (function (BABYLON) {
  19341. /**
  19342. * Class used to store all common mesh properties
  19343. */
  19344. var AbstractMesh = /** @class */ (function (_super) {
  19345. __extends(AbstractMesh, _super);
  19346. // Constructor
  19347. /**
  19348. * Creates a new AbstractMesh
  19349. * @param name defines the name of the mesh
  19350. * @param scene defines the hosting scene
  19351. */
  19352. function AbstractMesh(name, scene) {
  19353. if (scene === void 0) { scene = null; }
  19354. var _this = _super.call(this, name, scene, false) || this;
  19355. _this._facetNb = 0; // facet number
  19356. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19357. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19358. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19359. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19360. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19361. _this._subDiv = {
  19362. max: 1,
  19363. X: 1,
  19364. Y: 1,
  19365. Z: 1
  19366. };
  19367. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19368. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19369. // Events
  19370. /**
  19371. * An event triggered when this mesh collides with another one
  19372. */
  19373. _this.onCollideObservable = new BABYLON.Observable();
  19374. /**
  19375. * An event triggered when the collision's position changes
  19376. */
  19377. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19378. /**
  19379. * An event triggered when material is changed
  19380. */
  19381. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19382. // Properties
  19383. /**
  19384. * Gets or sets the orientation for POV movement & rotation
  19385. */
  19386. _this.definedFacingForward = true;
  19387. /**
  19388. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19389. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19390. * * 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.
  19391. * @see http://doc.babylonjs.com/features/occlusionquery
  19392. */
  19393. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19394. /**
  19395. * 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:
  19396. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19397. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19398. * * 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.
  19399. * @see http://doc.babylonjs.com/features/occlusionquery
  19400. */
  19401. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19402. /**
  19403. * 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.
  19404. * The default value is -1 which means don't break the query and wait till the result
  19405. * @see http://doc.babylonjs.com/features/occlusionquery
  19406. */
  19407. _this.occlusionRetryCount = -1;
  19408. _this._occlusionInternalRetryCounter = 0;
  19409. _this._isOccluded = false;
  19410. _this._isOcclusionQueryInProgress = false;
  19411. _this._visibility = 1.0;
  19412. /** Gets or sets the alpha index used to sort transparent meshes
  19413. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19414. */
  19415. _this.alphaIndex = Number.MAX_VALUE;
  19416. /**
  19417. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19418. */
  19419. _this.isVisible = true;
  19420. /**
  19421. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19422. */
  19423. _this.isPickable = true;
  19424. /**
  19425. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19426. */
  19427. _this.showBoundingBox = false;
  19428. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19429. _this.showSubMeshesBoundingBox = false;
  19430. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19431. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19432. */
  19433. _this.isBlocker = false;
  19434. /**
  19435. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19436. */
  19437. _this.enablePointerMoveEvents = false;
  19438. /**
  19439. * Specifies the rendering group id for this mesh (0 by default)
  19440. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19441. */
  19442. _this.renderingGroupId = 0;
  19443. _this._receiveShadows = false;
  19444. /**
  19445. * Gets or sets a boolean indicating if the outline must be rendered as well
  19446. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19447. */
  19448. _this.renderOutline = false;
  19449. /** Defines color to use when rendering outline */
  19450. _this.outlineColor = BABYLON.Color3.Red();
  19451. /** Define width to use when rendering outline */
  19452. _this.outlineWidth = 0.02;
  19453. /**
  19454. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19455. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19456. */
  19457. _this.renderOverlay = false;
  19458. /** Defines color to use when rendering overlay */
  19459. _this.overlayColor = BABYLON.Color3.Red();
  19460. /** Defines alpha to use when rendering overlay */
  19461. _this.overlayAlpha = 0.5;
  19462. _this._hasVertexAlpha = false;
  19463. _this._useVertexColors = true;
  19464. _this._computeBonesUsingShaders = true;
  19465. _this._numBoneInfluencers = 4;
  19466. _this._applyFog = true;
  19467. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19468. _this.useOctreeForRenderingSelection = true;
  19469. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19470. _this.useOctreeForPicking = true;
  19471. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19472. _this.useOctreeForCollisions = true;
  19473. _this._layerMask = 0x0FFFFFFF;
  19474. /**
  19475. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19476. */
  19477. _this.alwaysSelectAsActiveMesh = false;
  19478. /**
  19479. * Gets or sets the current action manager
  19480. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19481. */
  19482. _this.actionManager = null;
  19483. /**
  19484. * Gets or sets impostor used for physic simulation
  19485. * @see http://doc.babylonjs.com/features/physics_engine
  19486. */
  19487. _this.physicsImpostor = null;
  19488. // Collisions
  19489. _this._checkCollisions = false;
  19490. _this._collisionMask = -1;
  19491. _this._collisionGroup = -1;
  19492. /**
  19493. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19494. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19495. */
  19496. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19497. /**
  19498. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19499. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19500. */
  19501. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19502. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19503. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19504. // Edges
  19505. /**
  19506. * Defines edge width used when edgesRenderer is enabled
  19507. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19508. */
  19509. _this.edgesWidth = 1;
  19510. /**
  19511. * Defines edge color used when edgesRenderer is enabled
  19512. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19513. */
  19514. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19515. // Cache
  19516. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19517. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19518. /** @hidden */
  19519. _this._renderId = 0;
  19520. /** @hidden */
  19521. _this._intersectionsInProgress = new Array();
  19522. /** @hidden */
  19523. _this._unIndexed = false;
  19524. /** @hidden */
  19525. _this._lightSources = new Array();
  19526. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19527. if (collidedMesh === void 0) { collidedMesh = null; }
  19528. //TODO move this to the collision coordinator!
  19529. if (_this.getScene().workerCollisions)
  19530. newPosition.multiplyInPlace(_this._collider._radius);
  19531. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19532. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19533. _this.position.addInPlace(_this._diffPositionForCollisions);
  19534. }
  19535. if (collidedMesh) {
  19536. _this.onCollideObservable.notifyObservers(collidedMesh);
  19537. }
  19538. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19539. };
  19540. _this.getScene().addMesh(_this);
  19541. _this._resyncLightSources();
  19542. return _this;
  19543. }
  19544. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19545. /**
  19546. * No billboard
  19547. */
  19548. get: function () {
  19549. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19550. },
  19551. enumerable: true,
  19552. configurable: true
  19553. });
  19554. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19555. /** Billboard on X axis */
  19556. get: function () {
  19557. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19563. /** Billboard on Y axis */
  19564. get: function () {
  19565. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19566. },
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19571. /** Billboard on Z axis */
  19572. get: function () {
  19573. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19574. },
  19575. enumerable: true,
  19576. configurable: true
  19577. });
  19578. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19579. /** Billboard on all axes */
  19580. get: function () {
  19581. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19587. /**
  19588. * Gets the number of facets in the mesh
  19589. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19590. */
  19591. get: function () {
  19592. return this._facetNb;
  19593. },
  19594. enumerable: true,
  19595. configurable: true
  19596. });
  19597. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19598. /**
  19599. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19600. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19601. */
  19602. get: function () {
  19603. return this._partitioningSubdivisions;
  19604. },
  19605. set: function (nb) {
  19606. this._partitioningSubdivisions = nb;
  19607. },
  19608. enumerable: true,
  19609. configurable: true
  19610. });
  19611. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19612. /**
  19613. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19614. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19615. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19616. */
  19617. get: function () {
  19618. return this._partitioningBBoxRatio;
  19619. },
  19620. set: function (ratio) {
  19621. this._partitioningBBoxRatio = ratio;
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19627. /**
  19628. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19629. * Works only for updatable meshes.
  19630. * Doesn't work with multi-materials
  19631. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19632. */
  19633. get: function () {
  19634. return this._facetDepthSort;
  19635. },
  19636. set: function (sort) {
  19637. this._facetDepthSort = sort;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19643. /**
  19644. * The location (Vector3) where the facet depth sort must be computed from.
  19645. * By default, the active camera position.
  19646. * Used only when facet depth sort is enabled
  19647. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19648. */
  19649. get: function () {
  19650. return this._facetDepthSortFrom;
  19651. },
  19652. set: function (location) {
  19653. this._facetDepthSortFrom = location;
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19659. /**
  19660. * gets a boolean indicating if facetData is enabled
  19661. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19662. */
  19663. get: function () {
  19664. return this._facetDataEnabled;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. /** @hidden */
  19670. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19671. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19672. return false;
  19673. }
  19674. this._markSubMeshesAsMiscDirty();
  19675. return true;
  19676. };
  19677. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19678. /** Set a function to call when this mesh collides with another one */
  19679. set: function (callback) {
  19680. if (this._onCollideObserver) {
  19681. this.onCollideObservable.remove(this._onCollideObserver);
  19682. }
  19683. this._onCollideObserver = this.onCollideObservable.add(callback);
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19689. /** Set a function to call when the collision's position changes */
  19690. set: function (callback) {
  19691. if (this._onCollisionPositionChangeObserver) {
  19692. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19693. }
  19694. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19700. /**
  19701. * 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
  19702. * @see http://doc.babylonjs.com/features/occlusionquery
  19703. */
  19704. get: function () {
  19705. return this._isOccluded;
  19706. },
  19707. set: function (value) {
  19708. this._isOccluded = value;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19714. /**
  19715. * Flag to check the progress status of the query
  19716. * @see http://doc.babylonjs.com/features/occlusionquery
  19717. */
  19718. get: function () {
  19719. return this._isOcclusionQueryInProgress;
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19725. /**
  19726. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19727. */
  19728. get: function () {
  19729. return this._visibility;
  19730. },
  19731. /**
  19732. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19733. */
  19734. set: function (value) {
  19735. if (this._visibility === value) {
  19736. return;
  19737. }
  19738. this._visibility = value;
  19739. this._markSubMeshesAsMiscDirty();
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(AbstractMesh.prototype, "material", {
  19745. /** Gets or sets current material */
  19746. get: function () {
  19747. return this._material;
  19748. },
  19749. set: function (value) {
  19750. if (this._material === value) {
  19751. return;
  19752. }
  19753. this._material = value;
  19754. if (this.onMaterialChangedObservable.hasObservers) {
  19755. this.onMaterialChangedObservable.notifyObservers(this);
  19756. }
  19757. if (!this.subMeshes) {
  19758. return;
  19759. }
  19760. this._unBindEffect();
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19766. /**
  19767. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19768. * @see http://doc.babylonjs.com/babylon101/shadows
  19769. */
  19770. get: function () {
  19771. return this._receiveShadows;
  19772. },
  19773. set: function (value) {
  19774. if (this._receiveShadows === value) {
  19775. return;
  19776. }
  19777. this._receiveShadows = value;
  19778. this._markSubMeshesAsLightDirty();
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19784. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19785. get: function () {
  19786. return this._hasVertexAlpha;
  19787. },
  19788. set: function (value) {
  19789. if (this._hasVertexAlpha === value) {
  19790. return;
  19791. }
  19792. this._hasVertexAlpha = value;
  19793. this._markSubMeshesAsAttributesDirty();
  19794. this._markSubMeshesAsMiscDirty();
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19800. /** 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) */
  19801. get: function () {
  19802. return this._useVertexColors;
  19803. },
  19804. set: function (value) {
  19805. if (this._useVertexColors === value) {
  19806. return;
  19807. }
  19808. this._useVertexColors = value;
  19809. this._markSubMeshesAsAttributesDirty();
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19815. /**
  19816. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19817. */
  19818. get: function () {
  19819. return this._computeBonesUsingShaders;
  19820. },
  19821. set: function (value) {
  19822. if (this._computeBonesUsingShaders === value) {
  19823. return;
  19824. }
  19825. this._computeBonesUsingShaders = value;
  19826. this._markSubMeshesAsAttributesDirty();
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19832. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19833. get: function () {
  19834. return this._numBoneInfluencers;
  19835. },
  19836. set: function (value) {
  19837. if (this._numBoneInfluencers === value) {
  19838. return;
  19839. }
  19840. this._numBoneInfluencers = value;
  19841. this._markSubMeshesAsAttributesDirty();
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19847. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19848. get: function () {
  19849. return this._applyFog;
  19850. },
  19851. set: function (value) {
  19852. if (this._applyFog === value) {
  19853. return;
  19854. }
  19855. this._applyFog = value;
  19856. this._markSubMeshesAsMiscDirty();
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19862. /**
  19863. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19864. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19865. */
  19866. get: function () {
  19867. return this._layerMask;
  19868. },
  19869. set: function (value) {
  19870. if (value === this._layerMask) {
  19871. return;
  19872. }
  19873. this._layerMask = value;
  19874. this._resyncLightSources();
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19880. /**
  19881. * Gets or sets a collision mask used to mask collisions (default is -1).
  19882. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19883. */
  19884. get: function () {
  19885. return this._collisionMask;
  19886. },
  19887. set: function (mask) {
  19888. this._collisionMask = !isNaN(mask) ? mask : -1;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19894. /**
  19895. * Gets or sets the current collision group mask (-1 by default).
  19896. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19897. */
  19898. get: function () {
  19899. return this._collisionGroup;
  19900. },
  19901. set: function (mask) {
  19902. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19908. /** @hidden */
  19909. get: function () {
  19910. return null;
  19911. },
  19912. enumerable: true,
  19913. configurable: true
  19914. });
  19915. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19916. get: function () {
  19917. return this._skeleton;
  19918. },
  19919. /**
  19920. * Gets or sets a skeleton to apply skining transformations
  19921. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19922. */
  19923. set: function (value) {
  19924. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19925. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19926. }
  19927. if (value && value.needInitialSkinMatrix) {
  19928. value._registerMeshWithPoseMatrix(this);
  19929. }
  19930. this._skeleton = value;
  19931. if (!this._skeleton) {
  19932. this._bonesTransformMatrices = null;
  19933. }
  19934. this._markSubMeshesAsAttributesDirty();
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. /**
  19940. * Returns the string "AbstractMesh"
  19941. * @returns "AbstractMesh"
  19942. */
  19943. AbstractMesh.prototype.getClassName = function () {
  19944. return "AbstractMesh";
  19945. };
  19946. /**
  19947. * Gets a string representation of the current mesh
  19948. * @param fullDetails defines a boolean indicating if full details must be included
  19949. * @returns a string representation of the current mesh
  19950. */
  19951. AbstractMesh.prototype.toString = function (fullDetails) {
  19952. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19953. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19954. if (this._skeleton) {
  19955. ret += ", skeleton: " + this._skeleton.name;
  19956. }
  19957. if (fullDetails) {
  19958. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19959. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19960. }
  19961. return ret;
  19962. };
  19963. /** @hidden */
  19964. AbstractMesh.prototype._rebuild = function () {
  19965. if (this._occlusionQuery) {
  19966. this._occlusionQuery = null;
  19967. }
  19968. if (this._edgesRenderer) {
  19969. this._edgesRenderer._rebuild();
  19970. }
  19971. if (!this.subMeshes) {
  19972. return;
  19973. }
  19974. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19975. var subMesh = _a[_i];
  19976. subMesh._rebuild();
  19977. }
  19978. };
  19979. /** @hidden */
  19980. AbstractMesh.prototype._resyncLightSources = function () {
  19981. this._lightSources.length = 0;
  19982. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19983. var light = _a[_i];
  19984. if (!light.isEnabled()) {
  19985. continue;
  19986. }
  19987. if (light.canAffectMesh(this)) {
  19988. this._lightSources.push(light);
  19989. }
  19990. }
  19991. this._markSubMeshesAsLightDirty();
  19992. };
  19993. /** @hidden */
  19994. AbstractMesh.prototype._resyncLighSource = function (light) {
  19995. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19996. var index = this._lightSources.indexOf(light);
  19997. if (index === -1) {
  19998. if (!isIn) {
  19999. return;
  20000. }
  20001. this._lightSources.push(light);
  20002. }
  20003. else {
  20004. if (isIn) {
  20005. return;
  20006. }
  20007. this._lightSources.splice(index, 1);
  20008. }
  20009. this._markSubMeshesAsLightDirty();
  20010. };
  20011. /** @hidden */
  20012. AbstractMesh.prototype._unBindEffect = function () {
  20013. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20014. var subMesh = _a[_i];
  20015. subMesh.setEffect(null);
  20016. }
  20017. };
  20018. /** @hidden */
  20019. AbstractMesh.prototype._removeLightSource = function (light) {
  20020. var index = this._lightSources.indexOf(light);
  20021. if (index === -1) {
  20022. return;
  20023. }
  20024. this._lightSources.splice(index, 1);
  20025. this._markSubMeshesAsLightDirty();
  20026. };
  20027. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20028. if (!this.subMeshes) {
  20029. return;
  20030. }
  20031. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20032. var subMesh = _a[_i];
  20033. if (subMesh._materialDefines) {
  20034. func(subMesh._materialDefines);
  20035. }
  20036. }
  20037. };
  20038. /** @hidden */
  20039. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20040. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20041. };
  20042. /** @hidden */
  20043. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20044. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20045. };
  20046. /** @hidden */
  20047. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20048. if (!this.subMeshes) {
  20049. return;
  20050. }
  20051. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20052. var subMesh = _a[_i];
  20053. var material = subMesh.getMaterial();
  20054. if (material) {
  20055. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20056. }
  20057. }
  20058. };
  20059. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20060. /**
  20061. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20062. */
  20063. get: function () {
  20064. return this._scaling;
  20065. },
  20066. set: function (newScaling) {
  20067. this._scaling = newScaling;
  20068. if (this.physicsImpostor) {
  20069. this.physicsImpostor.forceUpdate();
  20070. }
  20071. },
  20072. enumerable: true,
  20073. configurable: true
  20074. });
  20075. // Methods
  20076. /**
  20077. * Disables the mesh edge rendering mode
  20078. * @returns the currentAbstractMesh
  20079. */
  20080. AbstractMesh.prototype.disableEdgesRendering = function () {
  20081. if (this._edgesRenderer) {
  20082. this._edgesRenderer.dispose();
  20083. this._edgesRenderer = null;
  20084. }
  20085. return this;
  20086. };
  20087. /**
  20088. * Enables the edge rendering mode on the mesh.
  20089. * This mode makes the mesh edges visible
  20090. * @param epsilon defines the maximal distance between two angles to detect a face
  20091. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20092. * @returns the currentAbstractMesh
  20093. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20094. */
  20095. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20096. if (epsilon === void 0) { epsilon = 0.95; }
  20097. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20098. this.disableEdgesRendering();
  20099. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20100. return this;
  20101. };
  20102. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20103. /**
  20104. * Gets the edgesRenderer associated with the mesh
  20105. */
  20106. get: function () {
  20107. return this._edgesRenderer;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20113. /**
  20114. * Returns true if the mesh is blocked. Implemented by child classes
  20115. */
  20116. get: function () {
  20117. return false;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. /**
  20123. * Returns the mesh itself by default. Implemented by child classes
  20124. * @param camera defines the camera to use to pick the right LOD level
  20125. * @returns the currentAbstractMesh
  20126. */
  20127. AbstractMesh.prototype.getLOD = function (camera) {
  20128. return this;
  20129. };
  20130. /**
  20131. * Returns 0 by default. Implemented by child classes
  20132. * @returns an integer
  20133. */
  20134. AbstractMesh.prototype.getTotalVertices = function () {
  20135. return 0;
  20136. };
  20137. /**
  20138. * Returns null by default. Implemented by child classes
  20139. * @returns null
  20140. */
  20141. AbstractMesh.prototype.getIndices = function () {
  20142. return null;
  20143. };
  20144. /**
  20145. * Returns the array of the requested vertex data kind. Implemented by child classes
  20146. * @param kind defines the vertex data kind to use
  20147. * @returns null
  20148. */
  20149. AbstractMesh.prototype.getVerticesData = function (kind) {
  20150. return null;
  20151. };
  20152. /**
  20153. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20154. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20155. * Note that a new underlying VertexBuffer object is created each call.
  20156. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20157. * @param kind defines vertex data kind:
  20158. * * BABYLON.VertexBuffer.PositionKind
  20159. * * BABYLON.VertexBuffer.UVKind
  20160. * * BABYLON.VertexBuffer.UV2Kind
  20161. * * BABYLON.VertexBuffer.UV3Kind
  20162. * * BABYLON.VertexBuffer.UV4Kind
  20163. * * BABYLON.VertexBuffer.UV5Kind
  20164. * * BABYLON.VertexBuffer.UV6Kind
  20165. * * BABYLON.VertexBuffer.ColorKind
  20166. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20167. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20168. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20169. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20170. * @param data defines the data source
  20171. * @param updatable defines if the data must be flagged as updatable (or static)
  20172. * @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
  20173. * @returns the current mesh
  20174. */
  20175. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20176. return this;
  20177. };
  20178. /**
  20179. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20180. * If the mesh has no geometry, it is simply returned as it is.
  20181. * @param kind defines vertex data kind:
  20182. * * BABYLON.VertexBuffer.PositionKind
  20183. * * BABYLON.VertexBuffer.UVKind
  20184. * * BABYLON.VertexBuffer.UV2Kind
  20185. * * BABYLON.VertexBuffer.UV3Kind
  20186. * * BABYLON.VertexBuffer.UV4Kind
  20187. * * BABYLON.VertexBuffer.UV5Kind
  20188. * * BABYLON.VertexBuffer.UV6Kind
  20189. * * BABYLON.VertexBuffer.ColorKind
  20190. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20191. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20192. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20193. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20194. * @param data defines the data source
  20195. * @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
  20196. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20197. * @returns the current mesh
  20198. */
  20199. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20200. return this;
  20201. };
  20202. /**
  20203. * Sets the mesh indices,
  20204. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20205. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20206. * @param totalVertices Defines the total number of vertices
  20207. * @returns the current mesh
  20208. */
  20209. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20210. return this;
  20211. };
  20212. /**
  20213. * Gets a boolean indicating if specific vertex data is present
  20214. * @param kind defines the vertex data kind to use
  20215. * @returns true is data kind is present
  20216. */
  20217. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20218. return false;
  20219. };
  20220. /**
  20221. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20222. * @returns a BoundingInfo
  20223. */
  20224. AbstractMesh.prototype.getBoundingInfo = function () {
  20225. if (this._masterMesh) {
  20226. return this._masterMesh.getBoundingInfo();
  20227. }
  20228. if (!this._boundingInfo) {
  20229. // this._boundingInfo is being created here
  20230. this._updateBoundingInfo();
  20231. }
  20232. // cannot be null.
  20233. return this._boundingInfo;
  20234. };
  20235. /**
  20236. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20237. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20238. * @returns the current mesh
  20239. */
  20240. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20241. if (includeDescendants === void 0) { includeDescendants = true; }
  20242. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20243. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20244. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20245. if (maxDimension === 0) {
  20246. return this;
  20247. }
  20248. var scale = 1 / maxDimension;
  20249. this.scaling.scaleInPlace(scale);
  20250. return this;
  20251. };
  20252. /**
  20253. * Overwrite the current bounding info
  20254. * @param boundingInfo defines the new bounding info
  20255. * @returns the current mesh
  20256. */
  20257. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20258. this._boundingInfo = boundingInfo;
  20259. return this;
  20260. };
  20261. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20262. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20263. get: function () {
  20264. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20265. },
  20266. enumerable: true,
  20267. configurable: true
  20268. });
  20269. /** @hidden */
  20270. AbstractMesh.prototype._preActivate = function () {
  20271. };
  20272. /** @hidden */
  20273. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20274. };
  20275. /** @hidden */
  20276. AbstractMesh.prototype._activate = function (renderId) {
  20277. this._renderId = renderId;
  20278. };
  20279. /**
  20280. * Gets the current world matrix
  20281. * @returns a Matrix
  20282. */
  20283. AbstractMesh.prototype.getWorldMatrix = function () {
  20284. if (this._masterMesh) {
  20285. return this._masterMesh.getWorldMatrix();
  20286. }
  20287. return _super.prototype.getWorldMatrix.call(this);
  20288. };
  20289. /** @hidden */
  20290. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20291. if (this._masterMesh) {
  20292. return this._masterMesh._getWorldMatrixDeterminant();
  20293. }
  20294. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20295. };
  20296. // ================================== Point of View Movement =================================
  20297. /**
  20298. * Perform relative position change from the point of view of behind the front of the mesh.
  20299. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20300. * Supports definition of mesh facing forward or backward
  20301. * @param amountRight defines the distance on the right axis
  20302. * @param amountUp defines the distance on the up axis
  20303. * @param amountForward defines the distance on the forward axis
  20304. * @returns the current mesh
  20305. */
  20306. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20307. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20308. return this;
  20309. };
  20310. /**
  20311. * Calculate relative position change from the point of view of behind the front of the mesh.
  20312. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20313. * Supports definition of mesh facing forward or backward
  20314. * @param amountRight defines the distance on the right axis
  20315. * @param amountUp defines the distance on the up axis
  20316. * @param amountForward defines the distance on the forward axis
  20317. * @returns the new displacement vector
  20318. */
  20319. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20320. var rotMatrix = new BABYLON.Matrix();
  20321. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20322. rotQuaternion.toRotationMatrix(rotMatrix);
  20323. var translationDelta = BABYLON.Vector3.Zero();
  20324. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20325. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20326. return translationDelta;
  20327. };
  20328. // ================================== Point of View Rotation =================================
  20329. /**
  20330. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20331. * Supports definition of mesh facing forward or backward
  20332. * @param flipBack defines the flip
  20333. * @param twirlClockwise defines the twirl
  20334. * @param tiltRight defines the tilt
  20335. * @returns the current mesh
  20336. */
  20337. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20338. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20339. return this;
  20340. };
  20341. /**
  20342. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20343. * Supports definition of mesh facing forward or backward.
  20344. * @param flipBack defines the flip
  20345. * @param twirlClockwise defines the twirl
  20346. * @param tiltRight defines the tilt
  20347. * @returns the new rotation vector
  20348. */
  20349. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20350. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20351. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20352. };
  20353. /**
  20354. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20355. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20356. * @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
  20357. * @returns the new bounding vectors
  20358. */
  20359. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20360. if (includeDescendants === void 0) { includeDescendants = true; }
  20361. if (predicate === void 0) { predicate = null; }
  20362. // Ensures that all world matrix will be recomputed.
  20363. this.getScene().incrementRenderId();
  20364. this.computeWorldMatrix(true);
  20365. var min;
  20366. var max;
  20367. var boundingInfo = this.getBoundingInfo();
  20368. if (!this.subMeshes) {
  20369. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20370. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20371. }
  20372. else {
  20373. min = boundingInfo.boundingBox.minimumWorld;
  20374. max = boundingInfo.boundingBox.maximumWorld;
  20375. }
  20376. if (includeDescendants) {
  20377. var descendants = this.getDescendants(false);
  20378. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20379. var descendant = descendants_1[_i];
  20380. var childMesh = descendant;
  20381. childMesh.computeWorldMatrix(true);
  20382. // Filters meshes based on custom predicate function.
  20383. if (predicate && !predicate(childMesh)) {
  20384. continue;
  20385. }
  20386. //make sure we have the needed params to get mix and max
  20387. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20388. continue;
  20389. }
  20390. var childBoundingInfo = childMesh.getBoundingInfo();
  20391. var boundingBox = childBoundingInfo.boundingBox;
  20392. var minBox = boundingBox.minimumWorld;
  20393. var maxBox = boundingBox.maximumWorld;
  20394. BABYLON.Tools.CheckExtends(minBox, min, max);
  20395. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20396. }
  20397. }
  20398. return {
  20399. min: min,
  20400. max: max
  20401. };
  20402. };
  20403. /** @hidden */
  20404. AbstractMesh.prototype._updateBoundingInfo = function () {
  20405. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20406. this._boundingInfo.update(this.worldMatrixFromCache);
  20407. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20408. return this;
  20409. };
  20410. /** @hidden */
  20411. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20412. if (!this.subMeshes) {
  20413. return this;
  20414. }
  20415. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20416. var subMesh = this.subMeshes[subIndex];
  20417. if (!subMesh.IsGlobal) {
  20418. subMesh.updateBoundingInfo(matrix);
  20419. }
  20420. }
  20421. return this;
  20422. };
  20423. /** @hidden */
  20424. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20425. // Bounding info
  20426. this._updateBoundingInfo();
  20427. };
  20428. /**
  20429. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20430. * A mesh is in the frustum if its bounding box intersects the frustum
  20431. * @param frustumPlanes defines the frustum to test
  20432. * @returns true if the mesh is in the frustum planes
  20433. */
  20434. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20435. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20436. };
  20437. /**
  20438. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20439. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20440. * @param frustumPlanes defines the frustum to test
  20441. * @returns true if the mesh is completely in the frustum planes
  20442. */
  20443. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20444. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20445. };
  20446. /**
  20447. * True if the mesh intersects another mesh or a SolidParticle object
  20448. * @param mesh defines a target mesh or SolidParticle to test
  20449. * @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)
  20450. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20451. * @returns true if there is an intersection
  20452. */
  20453. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20454. if (precise === void 0) { precise = false; }
  20455. if (!this._boundingInfo || !mesh._boundingInfo) {
  20456. return false;
  20457. }
  20458. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20459. return true;
  20460. }
  20461. if (includeDescendants) {
  20462. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20463. var child = _a[_i];
  20464. if (child.intersectsMesh(mesh, precise, true)) {
  20465. return true;
  20466. }
  20467. }
  20468. }
  20469. return false;
  20470. };
  20471. /**
  20472. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20473. * @param point defines the point to test
  20474. * @returns true if there is an intersection
  20475. */
  20476. AbstractMesh.prototype.intersectsPoint = function (point) {
  20477. if (!this._boundingInfo) {
  20478. return false;
  20479. }
  20480. return this._boundingInfo.intersectsPoint(point);
  20481. };
  20482. /**
  20483. * Gets the current physics impostor
  20484. * @see http://doc.babylonjs.com/features/physics_engine
  20485. * @returns a physics impostor or null
  20486. */
  20487. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20488. return this.physicsImpostor;
  20489. };
  20490. /**
  20491. * Gets the position of the current mesh in camera space
  20492. * @param camera defines the camera to use
  20493. * @returns a position
  20494. */
  20495. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20496. if (camera === void 0) { camera = null; }
  20497. if (!camera) {
  20498. camera = this.getScene().activeCamera;
  20499. }
  20500. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20501. };
  20502. /**
  20503. * Returns the distance from the mesh to the active camera
  20504. * @param camera defines the camera to use
  20505. * @returns the distance
  20506. */
  20507. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20508. if (camera === void 0) { camera = null; }
  20509. if (!camera) {
  20510. camera = this.getScene().activeCamera;
  20511. }
  20512. return this.absolutePosition.subtract(camera.position).length();
  20513. };
  20514. /**
  20515. * Apply a physic impulse to the mesh
  20516. * @param force defines the force to apply
  20517. * @param contactPoint defines where to apply the force
  20518. * @returns the current mesh
  20519. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20520. */
  20521. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20522. if (!this.physicsImpostor) {
  20523. return this;
  20524. }
  20525. this.physicsImpostor.applyImpulse(force, contactPoint);
  20526. return this;
  20527. };
  20528. /**
  20529. * Creates a physic joint between two meshes
  20530. * @param otherMesh defines the other mesh to use
  20531. * @param pivot1 defines the pivot to use on this mesh
  20532. * @param pivot2 defines the pivot to use on the other mesh
  20533. * @param options defines additional options (can be plugin dependent)
  20534. * @returns the current mesh
  20535. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20536. */
  20537. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20538. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20539. return this;
  20540. }
  20541. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20542. mainPivot: pivot1,
  20543. connectedPivot: pivot2,
  20544. nativeParams: options
  20545. });
  20546. return this;
  20547. };
  20548. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20549. // Collisions
  20550. /**
  20551. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20552. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20553. */
  20554. get: function () {
  20555. return this._checkCollisions;
  20556. },
  20557. set: function (collisionEnabled) {
  20558. this._checkCollisions = collisionEnabled;
  20559. if (this.getScene().workerCollisions) {
  20560. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20561. }
  20562. },
  20563. enumerable: true,
  20564. configurable: true
  20565. });
  20566. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20567. /**
  20568. * Gets Collider object used to compute collisions (not physics)
  20569. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20570. */
  20571. get: function () {
  20572. return this._collider;
  20573. },
  20574. enumerable: true,
  20575. configurable: true
  20576. });
  20577. /**
  20578. * Move the mesh using collision engine
  20579. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20580. * @param displacement defines the requested displacement vector
  20581. * @returns the current mesh
  20582. */
  20583. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20584. var globalPosition = this.getAbsolutePosition();
  20585. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20586. if (!this._collider) {
  20587. this._collider = new BABYLON.Collider();
  20588. }
  20589. this._collider._radius = this.ellipsoid;
  20590. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20591. return this;
  20592. };
  20593. // Submeshes octree
  20594. /**
  20595. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20596. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20597. * @param maxCapacity defines the maximum size of each block (64 by default)
  20598. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20599. * @returns the new octree
  20600. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20601. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20602. */
  20603. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20604. if (maxCapacity === void 0) { maxCapacity = 64; }
  20605. if (maxDepth === void 0) { maxDepth = 2; }
  20606. if (!this._submeshesOctree) {
  20607. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20608. }
  20609. this.computeWorldMatrix(true);
  20610. var boundingInfo = this.getBoundingInfo();
  20611. // Update octree
  20612. var bbox = boundingInfo.boundingBox;
  20613. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20614. return this._submeshesOctree;
  20615. };
  20616. // Collisions
  20617. /** @hidden */
  20618. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20619. this._generatePointsArray();
  20620. if (!this._positions) {
  20621. return this;
  20622. }
  20623. // Transformation
  20624. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20625. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20626. subMesh._lastColliderWorldVertices = [];
  20627. subMesh._trianglePlanes = [];
  20628. var start = subMesh.verticesStart;
  20629. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20630. for (var i = start; i < end; i++) {
  20631. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20632. }
  20633. }
  20634. // Collide
  20635. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20636. if (collider.collisionFound) {
  20637. collider.collidedMesh = this;
  20638. }
  20639. return this;
  20640. };
  20641. /** @hidden */
  20642. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20643. var subMeshes;
  20644. var len;
  20645. // Octrees
  20646. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20647. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20648. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20649. len = intersections.length;
  20650. subMeshes = intersections.data;
  20651. }
  20652. else {
  20653. subMeshes = this.subMeshes;
  20654. len = subMeshes.length;
  20655. }
  20656. for (var index = 0; index < len; index++) {
  20657. var subMesh = subMeshes[index];
  20658. // Bounding test
  20659. if (len > 1 && !subMesh._checkCollision(collider))
  20660. continue;
  20661. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20662. }
  20663. return this;
  20664. };
  20665. /** @hidden */
  20666. AbstractMesh.prototype._checkCollision = function (collider) {
  20667. // Bounding box test
  20668. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20669. return this;
  20670. // Transformation matrix
  20671. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20672. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20673. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20674. return this;
  20675. };
  20676. // Picking
  20677. /** @hidden */
  20678. AbstractMesh.prototype._generatePointsArray = function () {
  20679. return false;
  20680. };
  20681. /**
  20682. * Checks if the passed Ray intersects with the mesh
  20683. * @param ray defines the ray to use
  20684. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20685. * @returns the picking info
  20686. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20687. */
  20688. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20689. var pickingInfo = new BABYLON.PickingInfo();
  20690. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20691. return pickingInfo;
  20692. }
  20693. if (!this._generatePointsArray()) {
  20694. return pickingInfo;
  20695. }
  20696. var intersectInfo = null;
  20697. // Octrees
  20698. var subMeshes;
  20699. var len;
  20700. if (this._submeshesOctree && this.useOctreeForPicking) {
  20701. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20702. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20703. len = intersections.length;
  20704. subMeshes = intersections.data;
  20705. }
  20706. else {
  20707. subMeshes = this.subMeshes;
  20708. len = subMeshes.length;
  20709. }
  20710. for (var index = 0; index < len; index++) {
  20711. var subMesh = subMeshes[index];
  20712. // Bounding test
  20713. if (len > 1 && !subMesh.canIntersects(ray))
  20714. continue;
  20715. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20716. if (currentIntersectInfo) {
  20717. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20718. intersectInfo = currentIntersectInfo;
  20719. intersectInfo.subMeshId = index;
  20720. if (fastCheck) {
  20721. break;
  20722. }
  20723. }
  20724. }
  20725. }
  20726. if (intersectInfo) {
  20727. // Get picked point
  20728. var world = this.getWorldMatrix();
  20729. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20730. var direction = ray.direction.clone();
  20731. direction = direction.scale(intersectInfo.distance);
  20732. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20733. var pickedPoint = worldOrigin.add(worldDirection);
  20734. // Return result
  20735. pickingInfo.hit = true;
  20736. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20737. pickingInfo.pickedPoint = pickedPoint;
  20738. pickingInfo.pickedMesh = this;
  20739. pickingInfo.bu = intersectInfo.bu || 0;
  20740. pickingInfo.bv = intersectInfo.bv || 0;
  20741. pickingInfo.faceId = intersectInfo.faceId;
  20742. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20743. return pickingInfo;
  20744. }
  20745. return pickingInfo;
  20746. };
  20747. /**
  20748. * Clones the current mesh
  20749. * @param name defines the mesh name
  20750. * @param newParent defines the new mesh parent
  20751. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20752. * @returns the new mesh
  20753. */
  20754. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20755. return null;
  20756. };
  20757. /**
  20758. * Disposes all the submeshes of the current meshnp
  20759. * @returns the current mesh
  20760. */
  20761. AbstractMesh.prototype.releaseSubMeshes = function () {
  20762. if (this.subMeshes) {
  20763. while (this.subMeshes.length) {
  20764. this.subMeshes[0].dispose();
  20765. }
  20766. }
  20767. else {
  20768. this.subMeshes = new Array();
  20769. }
  20770. return this;
  20771. };
  20772. /**
  20773. * Releases resources associated with this abstract mesh.
  20774. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20775. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20776. */
  20777. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20778. var _this = this;
  20779. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20780. var index;
  20781. // Smart Array Retainers.
  20782. this.getScene().freeActiveMeshes();
  20783. this.getScene().freeRenderingGroups();
  20784. // Action manager
  20785. if (this.actionManager !== undefined && this.actionManager !== null) {
  20786. this.actionManager.dispose();
  20787. this.actionManager = null;
  20788. }
  20789. // Skeleton
  20790. this._skeleton = null;
  20791. // Physics
  20792. if (this.physicsImpostor) {
  20793. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20794. }
  20795. // Intersections in progress
  20796. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20797. var other = this._intersectionsInProgress[index];
  20798. var pos = other._intersectionsInProgress.indexOf(this);
  20799. other._intersectionsInProgress.splice(pos, 1);
  20800. }
  20801. this._intersectionsInProgress = [];
  20802. // Lights
  20803. var lights = this.getScene().lights;
  20804. lights.forEach(function (light) {
  20805. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20806. if (meshIndex !== -1) {
  20807. light.includedOnlyMeshes.splice(meshIndex, 1);
  20808. }
  20809. meshIndex = light.excludedMeshes.indexOf(_this);
  20810. if (meshIndex !== -1) {
  20811. light.excludedMeshes.splice(meshIndex, 1);
  20812. }
  20813. // Shadow generators
  20814. var generator = light.getShadowGenerator();
  20815. if (generator) {
  20816. var shadowMap = generator.getShadowMap();
  20817. if (shadowMap && shadowMap.renderList) {
  20818. meshIndex = shadowMap.renderList.indexOf(_this);
  20819. if (meshIndex !== -1) {
  20820. shadowMap.renderList.splice(meshIndex, 1);
  20821. }
  20822. }
  20823. }
  20824. });
  20825. // Edges
  20826. if (this._edgesRenderer) {
  20827. this._edgesRenderer.dispose();
  20828. this._edgesRenderer = null;
  20829. }
  20830. // SubMeshes
  20831. if (this.getClassName() !== "InstancedMesh") {
  20832. this.releaseSubMeshes();
  20833. }
  20834. // Octree
  20835. var sceneOctree = this.getScene().selectionOctree;
  20836. if (sceneOctree !== undefined && sceneOctree !== null) {
  20837. var index = sceneOctree.dynamicContent.indexOf(this);
  20838. if (index !== -1) {
  20839. sceneOctree.dynamicContent.splice(index, 1);
  20840. }
  20841. }
  20842. // Query
  20843. var engine = this.getScene().getEngine();
  20844. if (this._occlusionQuery) {
  20845. this._isOcclusionQueryInProgress = false;
  20846. engine.deleteQuery(this._occlusionQuery);
  20847. this._occlusionQuery = null;
  20848. }
  20849. // Engine
  20850. engine.wipeCaches();
  20851. // Remove from scene
  20852. this.getScene().removeMesh(this);
  20853. if (disposeMaterialAndTextures) {
  20854. if (this.material) {
  20855. this.material.dispose(false, true);
  20856. }
  20857. }
  20858. if (!doNotRecurse) {
  20859. // Particles
  20860. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20861. if (this.getScene().particleSystems[index].emitter === this) {
  20862. this.getScene().particleSystems[index].dispose();
  20863. index--;
  20864. }
  20865. }
  20866. }
  20867. // facet data
  20868. if (this._facetDataEnabled) {
  20869. this.disableFacetData();
  20870. }
  20871. this.onAfterWorldMatrixUpdateObservable.clear();
  20872. this.onCollideObservable.clear();
  20873. this.onCollisionPositionChangeObservable.clear();
  20874. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20875. };
  20876. /**
  20877. * Adds the passed mesh as a child to the current mesh
  20878. * @param mesh defines the child mesh
  20879. * @returns the current mesh
  20880. */
  20881. AbstractMesh.prototype.addChild = function (mesh) {
  20882. mesh.setParent(this);
  20883. return this;
  20884. };
  20885. /**
  20886. * Removes the passed mesh from the current mesh children list
  20887. * @param mesh defines the child mesh
  20888. * @returns the current mesh
  20889. */
  20890. AbstractMesh.prototype.removeChild = function (mesh) {
  20891. mesh.setParent(null);
  20892. return this;
  20893. };
  20894. // Facet data
  20895. /** @hidden */
  20896. AbstractMesh.prototype._initFacetData = function () {
  20897. if (!this._facetNormals) {
  20898. this._facetNormals = new Array();
  20899. }
  20900. if (!this._facetPositions) {
  20901. this._facetPositions = new Array();
  20902. }
  20903. if (!this._facetPartitioning) {
  20904. this._facetPartitioning = new Array();
  20905. }
  20906. this._facetNb = (this.getIndices().length / 3) | 0;
  20907. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20908. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20909. for (var f = 0; f < this._facetNb; f++) {
  20910. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20911. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20912. }
  20913. this._facetDataEnabled = true;
  20914. return this;
  20915. };
  20916. /**
  20917. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20918. * This method can be called within the render loop.
  20919. * 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
  20920. * @returns the current mesh
  20921. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20922. */
  20923. AbstractMesh.prototype.updateFacetData = function () {
  20924. if (!this._facetDataEnabled) {
  20925. this._initFacetData();
  20926. }
  20927. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20928. var indices = this.getIndices();
  20929. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20930. var bInfo = this.getBoundingInfo();
  20931. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20932. // init arrays, matrix and sort function on first call
  20933. this._facetDepthSortEnabled = true;
  20934. if (indices instanceof Uint16Array) {
  20935. this._depthSortedIndices = new Uint16Array(indices);
  20936. }
  20937. else if (indices instanceof Uint32Array) {
  20938. this._depthSortedIndices = new Uint32Array(indices);
  20939. }
  20940. else {
  20941. var needs32bits = false;
  20942. for (var i = 0; i < indices.length; i++) {
  20943. if (indices[i] > 65535) {
  20944. needs32bits = true;
  20945. break;
  20946. }
  20947. }
  20948. if (needs32bits) {
  20949. this._depthSortedIndices = new Uint32Array(indices);
  20950. }
  20951. else {
  20952. this._depthSortedIndices = new Uint16Array(indices);
  20953. }
  20954. }
  20955. this._facetDepthSortFunction = function (f1, f2) {
  20956. return (f2.sqDistance - f1.sqDistance);
  20957. };
  20958. if (!this._facetDepthSortFrom) {
  20959. var camera = this.getScene().activeCamera;
  20960. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20961. }
  20962. this._depthSortedFacets = [];
  20963. for (var f = 0; f < this._facetNb; f++) {
  20964. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20965. this._depthSortedFacets.push(depthSortedFacet);
  20966. }
  20967. this._invertedMatrix = BABYLON.Matrix.Identity();
  20968. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20969. }
  20970. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20971. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20972. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20973. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20974. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20975. this._subDiv.max = this._partitioningSubdivisions;
  20976. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20977. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20978. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20979. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20980. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20981. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20982. // set the parameters for ComputeNormals()
  20983. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20984. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20985. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20986. this._facetParameters.bInfo = bInfo;
  20987. this._facetParameters.bbSize = this._bbSize;
  20988. this._facetParameters.subDiv = this._subDiv;
  20989. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20990. this._facetParameters.depthSort = this._facetDepthSort;
  20991. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20992. this.computeWorldMatrix(true);
  20993. this._worldMatrix.invertToRef(this._invertedMatrix);
  20994. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20995. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20996. }
  20997. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20998. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20999. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21000. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21001. var l = (this._depthSortedIndices.length / 3) | 0;
  21002. for (var f = 0; f < l; f++) {
  21003. var sind = this._depthSortedFacets[f].ind;
  21004. this._depthSortedIndices[f * 3] = indices[sind];
  21005. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21006. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21007. }
  21008. this.updateIndices(this._depthSortedIndices);
  21009. }
  21010. return this;
  21011. };
  21012. /**
  21013. * Returns the facetLocalNormals array.
  21014. * The normals are expressed in the mesh local spac
  21015. * @returns an array of Vector3
  21016. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21017. */
  21018. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21019. if (!this._facetNormals) {
  21020. this.updateFacetData();
  21021. }
  21022. return this._facetNormals;
  21023. };
  21024. /**
  21025. * Returns the facetLocalPositions array.
  21026. * The facet positions are expressed in the mesh local space
  21027. * @returns an array of Vector3
  21028. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21029. */
  21030. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21031. if (!this._facetPositions) {
  21032. this.updateFacetData();
  21033. }
  21034. return this._facetPositions;
  21035. };
  21036. /**
  21037. * Returns the facetLocalPartioning array
  21038. * @returns an array of array of numbers
  21039. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21040. */
  21041. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21042. if (!this._facetPartitioning) {
  21043. this.updateFacetData();
  21044. }
  21045. return this._facetPartitioning;
  21046. };
  21047. /**
  21048. * Returns the i-th facet position in the world system.
  21049. * This method allocates a new Vector3 per call
  21050. * @param i defines the facet index
  21051. * @returns a new Vector3
  21052. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21053. */
  21054. AbstractMesh.prototype.getFacetPosition = function (i) {
  21055. var pos = BABYLON.Vector3.Zero();
  21056. this.getFacetPositionToRef(i, pos);
  21057. return pos;
  21058. };
  21059. /**
  21060. * Sets the reference Vector3 with the i-th facet position in the world system
  21061. * @param i defines the facet index
  21062. * @param ref defines the target vector
  21063. * @returns the current mesh
  21064. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21065. */
  21066. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21067. var localPos = (this.getFacetLocalPositions())[i];
  21068. var world = this.getWorldMatrix();
  21069. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21070. return this;
  21071. };
  21072. /**
  21073. * Returns the i-th facet normal in the world system.
  21074. * This method allocates a new Vector3 per call
  21075. * @param i defines the facet index
  21076. * @returns a new Vector3
  21077. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21078. */
  21079. AbstractMesh.prototype.getFacetNormal = function (i) {
  21080. var norm = BABYLON.Vector3.Zero();
  21081. this.getFacetNormalToRef(i, norm);
  21082. return norm;
  21083. };
  21084. /**
  21085. * Sets the reference Vector3 with the i-th facet normal in the world system
  21086. * @param i defines the facet index
  21087. * @param ref defines the target vector
  21088. * @returns the current mesh
  21089. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21090. */
  21091. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21092. var localNorm = (this.getFacetLocalNormals())[i];
  21093. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21094. return this;
  21095. };
  21096. /**
  21097. * 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)
  21098. * @param x defines x coordinate
  21099. * @param y defines y coordinate
  21100. * @param z defines z coordinate
  21101. * @returns the array of facet indexes
  21102. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21103. */
  21104. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21105. var bInfo = this.getBoundingInfo();
  21106. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21107. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21108. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21109. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21110. return null;
  21111. }
  21112. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21113. };
  21114. /**
  21115. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21116. * @param projected sets as the (x,y,z) world projection on the facet
  21117. * @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
  21118. * @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
  21119. * @param x defines x coordinate
  21120. * @param y defines y coordinate
  21121. * @param z defines z coordinate
  21122. * @returns the face index if found (or null instead)
  21123. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21124. */
  21125. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21126. if (checkFace === void 0) { checkFace = false; }
  21127. if (facing === void 0) { facing = true; }
  21128. var world = this.getWorldMatrix();
  21129. var invMat = BABYLON.Tmp.Matrix[5];
  21130. world.invertToRef(invMat);
  21131. var invVect = BABYLON.Tmp.Vector3[8];
  21132. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21133. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21134. if (projected) {
  21135. // tranform the local computed projected vector to world coordinates
  21136. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21137. }
  21138. return closest;
  21139. };
  21140. /**
  21141. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21142. * @param projected sets as the (x,y,z) local projection on the facet
  21143. * @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
  21144. * @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
  21145. * @param x defines x coordinate
  21146. * @param y defines y coordinate
  21147. * @param z defines z coordinate
  21148. * @returns the face index if found (or null instead)
  21149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21150. */
  21151. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21152. if (checkFace === void 0) { checkFace = false; }
  21153. if (facing === void 0) { facing = true; }
  21154. var closest = null;
  21155. var tmpx = 0.0;
  21156. var tmpy = 0.0;
  21157. var tmpz = 0.0;
  21158. var d = 0.0; // tmp dot facet normal * facet position
  21159. var t0 = 0.0;
  21160. var projx = 0.0;
  21161. var projy = 0.0;
  21162. var projz = 0.0;
  21163. // Get all the facets in the same partitioning block than (x, y, z)
  21164. var facetPositions = this.getFacetLocalPositions();
  21165. var facetNormals = this.getFacetLocalNormals();
  21166. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21167. if (!facetsInBlock) {
  21168. return null;
  21169. }
  21170. // Get the closest facet to (x, y, z)
  21171. var shortest = Number.MAX_VALUE; // init distance vars
  21172. var tmpDistance = shortest;
  21173. var fib; // current facet in the block
  21174. var norm; // current facet normal
  21175. var p0; // current facet barycenter position
  21176. // loop on all the facets in the current partitioning block
  21177. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21178. fib = facetsInBlock[idx];
  21179. norm = facetNormals[fib];
  21180. p0 = facetPositions[fib];
  21181. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21182. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21183. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21184. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21185. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21186. projx = x + norm.x * t0;
  21187. projy = y + norm.y * t0;
  21188. projz = z + norm.z * t0;
  21189. tmpx = projx - x;
  21190. tmpy = projy - y;
  21191. tmpz = projz - z;
  21192. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21193. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21194. shortest = tmpDistance;
  21195. closest = fib;
  21196. if (projected) {
  21197. projected.x = projx;
  21198. projected.y = projy;
  21199. projected.z = projz;
  21200. }
  21201. }
  21202. }
  21203. }
  21204. return closest;
  21205. };
  21206. /**
  21207. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21208. * @returns the parameters
  21209. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21210. */
  21211. AbstractMesh.prototype.getFacetDataParameters = function () {
  21212. return this._facetParameters;
  21213. };
  21214. /**
  21215. * Disables the feature FacetData and frees the related memory
  21216. * @returns the current mesh
  21217. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21218. */
  21219. AbstractMesh.prototype.disableFacetData = function () {
  21220. if (this._facetDataEnabled) {
  21221. this._facetDataEnabled = false;
  21222. this._facetPositions = new Array();
  21223. this._facetNormals = new Array();
  21224. this._facetPartitioning = new Array();
  21225. this._facetParameters = null;
  21226. this._depthSortedIndices = new Uint32Array(0);
  21227. }
  21228. return this;
  21229. };
  21230. /**
  21231. * Updates the AbstractMesh indices array
  21232. * @param indices defines the data source
  21233. * @returns the current mesh
  21234. */
  21235. AbstractMesh.prototype.updateIndices = function (indices) {
  21236. return this;
  21237. };
  21238. /**
  21239. * Creates new normals data for the mesh
  21240. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21241. * @returns the current mesh
  21242. */
  21243. AbstractMesh.prototype.createNormals = function (updatable) {
  21244. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21245. var indices = this.getIndices();
  21246. var normals;
  21247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21248. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21249. }
  21250. else {
  21251. normals = [];
  21252. }
  21253. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21254. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21255. return this;
  21256. };
  21257. /**
  21258. * Align the mesh with a normal
  21259. * @param normal defines the normal to use
  21260. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21261. * @returns the current mesh
  21262. */
  21263. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21264. if (!upDirection) {
  21265. upDirection = BABYLON.Axis.Y;
  21266. }
  21267. var axisX = BABYLON.Tmp.Vector3[0];
  21268. var axisZ = BABYLON.Tmp.Vector3[1];
  21269. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21270. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21271. if (this.rotationQuaternion) {
  21272. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21273. }
  21274. else {
  21275. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21276. }
  21277. return this;
  21278. };
  21279. /** @hidden */
  21280. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21281. var engine = this.getEngine();
  21282. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21283. this._isOccluded = false;
  21284. return;
  21285. }
  21286. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21287. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21288. if (isOcclusionQueryAvailable) {
  21289. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21290. this._isOcclusionQueryInProgress = false;
  21291. this._occlusionInternalRetryCounter = 0;
  21292. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21293. }
  21294. else {
  21295. this._occlusionInternalRetryCounter++;
  21296. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21297. this._isOcclusionQueryInProgress = false;
  21298. this._occlusionInternalRetryCounter = 0;
  21299. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21300. // if strict continue the last state of the object.
  21301. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21302. }
  21303. else {
  21304. return;
  21305. }
  21306. }
  21307. }
  21308. var scene = this.getScene();
  21309. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21310. if (!this._occlusionQuery) {
  21311. this._occlusionQuery = engine.createQuery();
  21312. }
  21313. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21314. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21315. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21316. this._isOcclusionQueryInProgress = true;
  21317. };
  21318. /** No occlusion */
  21319. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21320. /** Occlusion set to optimisitic */
  21321. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21322. /** Occlusion set to strict */
  21323. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21324. /** Use an accurante occlusion algorithm */
  21325. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21326. /** Use a conservative occlusion algorithm */
  21327. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21328. return AbstractMesh;
  21329. }(BABYLON.TransformNode));
  21330. BABYLON.AbstractMesh = AbstractMesh;
  21331. })(BABYLON || (BABYLON = {}));
  21332. //# sourceMappingURL=babylon.abstractMesh.js.map
  21333. var BABYLON;
  21334. (function (BABYLON) {
  21335. /**
  21336. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21337. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21338. * 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.
  21339. */
  21340. var Light = /** @class */ (function (_super) {
  21341. __extends(Light, _super);
  21342. /**
  21343. * Creates a Light object in the scene.
  21344. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21345. * @param name The firendly name of the light
  21346. * @param scene The scene the light belongs too
  21347. */
  21348. function Light(name, scene) {
  21349. var _this = _super.call(this, name, scene) || this;
  21350. /**
  21351. * Diffuse gives the basic color to an object.
  21352. */
  21353. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21354. /**
  21355. * Specular produces a highlight color on an object.
  21356. * Note: This is note affecting PBR materials.
  21357. */
  21358. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21359. /**
  21360. * Strength of the light.
  21361. * Note: By default it is define in the framework own unit.
  21362. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21363. */
  21364. _this.intensity = 1.0;
  21365. /**
  21366. * Defines how far from the source the light is impacting in scene units.
  21367. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21368. */
  21369. _this.range = Number.MAX_VALUE;
  21370. /**
  21371. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21372. * of light.
  21373. */
  21374. _this._photometricScale = 1.0;
  21375. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21376. _this._radius = 0.00001;
  21377. /**
  21378. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21379. * exceeding the number allowed of the materials.
  21380. */
  21381. _this.renderPriority = 0;
  21382. _this._shadowEnabled = true;
  21383. _this._excludeWithLayerMask = 0;
  21384. _this._includeOnlyWithLayerMask = 0;
  21385. _this._lightmapMode = 0;
  21386. /**
  21387. * @hidden Internal use only.
  21388. */
  21389. _this._excludedMeshesIds = new Array();
  21390. /**
  21391. * @hidden Internal use only.
  21392. */
  21393. _this._includedOnlyMeshesIds = new Array();
  21394. _this.getScene().addLight(_this);
  21395. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21396. _this._buildUniformLayout();
  21397. _this.includedOnlyMeshes = new Array();
  21398. _this.excludedMeshes = new Array();
  21399. _this._resyncMeshes();
  21400. return _this;
  21401. }
  21402. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21403. /**
  21404. * If every light affecting the material is in this lightmapMode,
  21405. * material.lightmapTexture adds or multiplies
  21406. * (depends on material.useLightmapAsShadowmap)
  21407. * after every other light calculations.
  21408. */
  21409. get: function () {
  21410. return Light._LIGHTMAP_DEFAULT;
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21416. /**
  21417. * material.lightmapTexture as only diffuse lighting from this light
  21418. * adds only specular lighting from this light
  21419. * adds dynamic shadows
  21420. */
  21421. get: function () {
  21422. return Light._LIGHTMAP_SPECULAR;
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21428. /**
  21429. * material.lightmapTexture as only lighting
  21430. * no light calculation from this light
  21431. * only adds dynamic shadows from this light
  21432. */
  21433. get: function () {
  21434. return Light._LIGHTMAP_SHADOWSONLY;
  21435. },
  21436. enumerable: true,
  21437. configurable: true
  21438. });
  21439. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21440. /**
  21441. * Each light type uses the default quantity according to its type:
  21442. * point/spot lights use luminous intensity
  21443. * directional lights use illuminance
  21444. */
  21445. get: function () {
  21446. return Light._INTENSITYMODE_AUTOMATIC;
  21447. },
  21448. enumerable: true,
  21449. configurable: true
  21450. });
  21451. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21452. /**
  21453. * lumen (lm)
  21454. */
  21455. get: function () {
  21456. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21462. /**
  21463. * candela (lm/sr)
  21464. */
  21465. get: function () {
  21466. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21472. /**
  21473. * lux (lm/m^2)
  21474. */
  21475. get: function () {
  21476. return Light._INTENSITYMODE_ILLUMINANCE;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21482. /**
  21483. * nit (cd/m^2)
  21484. */
  21485. get: function () {
  21486. return Light._INTENSITYMODE_LUMINANCE;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21492. /**
  21493. * Light type const id of the point light.
  21494. */
  21495. get: function () {
  21496. return Light._LIGHTTYPEID_POINTLIGHT;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21502. /**
  21503. * Light type const id of the directional light.
  21504. */
  21505. get: function () {
  21506. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21507. },
  21508. enumerable: true,
  21509. configurable: true
  21510. });
  21511. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21512. /**
  21513. * Light type const id of the spot light.
  21514. */
  21515. get: function () {
  21516. return Light._LIGHTTYPEID_SPOTLIGHT;
  21517. },
  21518. enumerable: true,
  21519. configurable: true
  21520. });
  21521. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21522. /**
  21523. * Light type const id of the hemispheric light.
  21524. */
  21525. get: function () {
  21526. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. Object.defineProperty(Light.prototype, "intensityMode", {
  21532. /**
  21533. * Gets the photometric scale used to interpret the intensity.
  21534. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21535. */
  21536. get: function () {
  21537. return this._intensityMode;
  21538. },
  21539. /**
  21540. * Sets the photometric scale used to interpret the intensity.
  21541. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21542. */
  21543. set: function (value) {
  21544. this._intensityMode = value;
  21545. this._computePhotometricScale();
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. ;
  21551. ;
  21552. Object.defineProperty(Light.prototype, "radius", {
  21553. /**
  21554. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21555. */
  21556. get: function () {
  21557. return this._radius;
  21558. },
  21559. /**
  21560. * sets the light radius used by PBR Materials to simulate soft area lights.
  21561. */
  21562. set: function (value) {
  21563. this._radius = value;
  21564. this._computePhotometricScale();
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. ;
  21570. ;
  21571. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21572. /**
  21573. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21574. * the current shadow generator.
  21575. */
  21576. get: function () {
  21577. return this._shadowEnabled;
  21578. },
  21579. /**
  21580. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21581. * the current shadow generator.
  21582. */
  21583. set: function (value) {
  21584. if (this._shadowEnabled === value) {
  21585. return;
  21586. }
  21587. this._shadowEnabled = value;
  21588. this._markMeshesAsLightDirty();
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21594. /**
  21595. * Gets the only meshes impacted by this light.
  21596. */
  21597. get: function () {
  21598. return this._includedOnlyMeshes;
  21599. },
  21600. /**
  21601. * Sets the only meshes impacted by this light.
  21602. */
  21603. set: function (value) {
  21604. this._includedOnlyMeshes = value;
  21605. this._hookArrayForIncludedOnly(value);
  21606. },
  21607. enumerable: true,
  21608. configurable: true
  21609. });
  21610. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21611. /**
  21612. * Gets the meshes not impacted by this light.
  21613. */
  21614. get: function () {
  21615. return this._excludedMeshes;
  21616. },
  21617. /**
  21618. * Sets the meshes not impacted by this light.
  21619. */
  21620. set: function (value) {
  21621. this._excludedMeshes = value;
  21622. this._hookArrayForExcluded(value);
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21628. /**
  21629. * Gets the layer id use to find what meshes are not impacted by the light.
  21630. * Inactive if 0
  21631. */
  21632. get: function () {
  21633. return this._excludeWithLayerMask;
  21634. },
  21635. /**
  21636. * Sets the layer id use to find what meshes are not impacted by the light.
  21637. * Inactive if 0
  21638. */
  21639. set: function (value) {
  21640. this._excludeWithLayerMask = value;
  21641. this._resyncMeshes();
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21647. /**
  21648. * Gets the layer id use to find what meshes are impacted by the light.
  21649. * Inactive if 0
  21650. */
  21651. get: function () {
  21652. return this._includeOnlyWithLayerMask;
  21653. },
  21654. /**
  21655. * Sets the layer id use to find what meshes are impacted by the light.
  21656. * Inactive if 0
  21657. */
  21658. set: function (value) {
  21659. this._includeOnlyWithLayerMask = value;
  21660. this._resyncMeshes();
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Light.prototype, "lightmapMode", {
  21666. /**
  21667. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21668. */
  21669. get: function () {
  21670. return this._lightmapMode;
  21671. },
  21672. /**
  21673. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21674. */
  21675. set: function (value) {
  21676. if (this._lightmapMode === value) {
  21677. return;
  21678. }
  21679. this._lightmapMode = value;
  21680. this._markMeshesAsLightDirty();
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. /**
  21686. * Returns the string "Light".
  21687. * @returns the class name
  21688. */
  21689. Light.prototype.getClassName = function () {
  21690. return "Light";
  21691. };
  21692. /**
  21693. * Converts the light information to a readable string for debug purpose.
  21694. * @param fullDetails Supports for multiple levels of logging within scene loading
  21695. * @returns the human readable light info
  21696. */
  21697. Light.prototype.toString = function (fullDetails) {
  21698. var ret = "Name: " + this.name;
  21699. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21700. if (this.animations) {
  21701. for (var i = 0; i < this.animations.length; i++) {
  21702. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21703. }
  21704. }
  21705. if (fullDetails) {
  21706. }
  21707. return ret;
  21708. };
  21709. /**
  21710. * Set the enabled state of this node.
  21711. * @param value - the new enabled state
  21712. */
  21713. Light.prototype.setEnabled = function (value) {
  21714. _super.prototype.setEnabled.call(this, value);
  21715. this._resyncMeshes();
  21716. };
  21717. /**
  21718. * Returns the Light associated shadow generator if any.
  21719. * @return the associated shadow generator.
  21720. */
  21721. Light.prototype.getShadowGenerator = function () {
  21722. return this._shadowGenerator;
  21723. };
  21724. /**
  21725. * Returns a Vector3, the absolute light position in the World.
  21726. * @returns the world space position of the light
  21727. */
  21728. Light.prototype.getAbsolutePosition = function () {
  21729. return BABYLON.Vector3.Zero();
  21730. };
  21731. /**
  21732. * Specifies if the light will affect the passed mesh.
  21733. * @param mesh The mesh to test against the light
  21734. * @return true the mesh is affected otherwise, false.
  21735. */
  21736. Light.prototype.canAffectMesh = function (mesh) {
  21737. if (!mesh) {
  21738. return true;
  21739. }
  21740. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21741. return false;
  21742. }
  21743. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21744. return false;
  21745. }
  21746. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21747. return false;
  21748. }
  21749. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21750. return false;
  21751. }
  21752. return true;
  21753. };
  21754. /**
  21755. * Computes and Returns the light World matrix.
  21756. * @returns the world matrix
  21757. */
  21758. Light.prototype.getWorldMatrix = function () {
  21759. this._currentRenderId = this.getScene().getRenderId();
  21760. this._childRenderId = this._currentRenderId;
  21761. var worldMatrix = this._getWorldMatrix();
  21762. if (this.parent && this.parent.getWorldMatrix) {
  21763. if (!this._parentedWorldMatrix) {
  21764. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21765. }
  21766. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21767. this._markSyncedWithParent();
  21768. return this._parentedWorldMatrix;
  21769. }
  21770. return worldMatrix;
  21771. };
  21772. /**
  21773. * Sort function to order lights for rendering.
  21774. * @param a First Light object to compare to second.
  21775. * @param b Second Light object to compare first.
  21776. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21777. */
  21778. Light.CompareLightsPriority = function (a, b) {
  21779. //shadow-casting lights have priority over non-shadow-casting lights
  21780. //the renderPrioirty is a secondary sort criterion
  21781. if (a.shadowEnabled !== b.shadowEnabled) {
  21782. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21783. }
  21784. return b.renderPriority - a.renderPriority;
  21785. };
  21786. /**
  21787. * Releases resources associated with this node.
  21788. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21789. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21790. */
  21791. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21792. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21793. if (this._shadowGenerator) {
  21794. this._shadowGenerator.dispose();
  21795. this._shadowGenerator = null;
  21796. }
  21797. // Animations
  21798. this.getScene().stopAnimation(this);
  21799. // Remove from meshes
  21800. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21801. var mesh = _a[_i];
  21802. mesh._removeLightSource(this);
  21803. }
  21804. this._uniformBuffer.dispose();
  21805. // Remove from scene
  21806. this.getScene().removeLight(this);
  21807. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21808. };
  21809. /**
  21810. * Returns the light type ID (integer).
  21811. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21812. */
  21813. Light.prototype.getTypeID = function () {
  21814. return 0;
  21815. };
  21816. /**
  21817. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21818. * @returns the scaled intensity in intensity mode unit
  21819. */
  21820. Light.prototype.getScaledIntensity = function () {
  21821. return this._photometricScale * this.intensity;
  21822. };
  21823. /**
  21824. * Returns a new Light object, named "name", from the current one.
  21825. * @param name The name of the cloned light
  21826. * @returns the new created light
  21827. */
  21828. Light.prototype.clone = function (name) {
  21829. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21830. if (!constructor) {
  21831. return null;
  21832. }
  21833. return BABYLON.SerializationHelper.Clone(constructor, this);
  21834. };
  21835. /**
  21836. * Serializes the current light into a Serialization object.
  21837. * @returns the serialized object.
  21838. */
  21839. Light.prototype.serialize = function () {
  21840. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21841. // Type
  21842. serializationObject.type = this.getTypeID();
  21843. // Parent
  21844. if (this.parent) {
  21845. serializationObject.parentId = this.parent.id;
  21846. }
  21847. // Inclusion / exclusions
  21848. if (this.excludedMeshes.length > 0) {
  21849. serializationObject.excludedMeshesIds = [];
  21850. this.excludedMeshes.forEach(function (mesh) {
  21851. serializationObject.excludedMeshesIds.push(mesh.id);
  21852. });
  21853. }
  21854. if (this.includedOnlyMeshes.length > 0) {
  21855. serializationObject.includedOnlyMeshesIds = [];
  21856. this.includedOnlyMeshes.forEach(function (mesh) {
  21857. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21858. });
  21859. }
  21860. // Animations
  21861. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21862. serializationObject.ranges = this.serializeAnimationRanges();
  21863. return serializationObject;
  21864. };
  21865. /**
  21866. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21867. * This new light is named "name" and added to the passed scene.
  21868. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21869. * @param name The friendly name of the light
  21870. * @param scene The scene the new light will belong to
  21871. * @returns the constructor function
  21872. */
  21873. Light.GetConstructorFromName = function (type, name, scene) {
  21874. switch (type) {
  21875. case 0:
  21876. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21877. case 1:
  21878. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21879. case 2:
  21880. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21881. case 3:
  21882. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21883. }
  21884. return null;
  21885. };
  21886. /**
  21887. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21888. * @param parsedLight The JSON representation of the light
  21889. * @param scene The scene to create the parsed light in
  21890. * @returns the created light after parsing
  21891. */
  21892. Light.Parse = function (parsedLight, scene) {
  21893. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21894. if (!constructor) {
  21895. return null;
  21896. }
  21897. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21898. // Inclusion / exclusions
  21899. if (parsedLight.excludedMeshesIds) {
  21900. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21901. }
  21902. if (parsedLight.includedOnlyMeshesIds) {
  21903. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21904. }
  21905. // Parent
  21906. if (parsedLight.parentId) {
  21907. light._waitingParentId = parsedLight.parentId;
  21908. }
  21909. // Animations
  21910. if (parsedLight.animations) {
  21911. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21912. var parsedAnimation = parsedLight.animations[animationIndex];
  21913. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21914. }
  21915. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21916. }
  21917. if (parsedLight.autoAnimate) {
  21918. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21919. }
  21920. return light;
  21921. };
  21922. Light.prototype._hookArrayForExcluded = function (array) {
  21923. var _this = this;
  21924. var oldPush = array.push;
  21925. array.push = function () {
  21926. var items = [];
  21927. for (var _i = 0; _i < arguments.length; _i++) {
  21928. items[_i] = arguments[_i];
  21929. }
  21930. var result = oldPush.apply(array, items);
  21931. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21932. var item = items_1[_a];
  21933. item._resyncLighSource(_this);
  21934. }
  21935. return result;
  21936. };
  21937. var oldSplice = array.splice;
  21938. array.splice = function (index, deleteCount) {
  21939. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21940. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21941. var item = deleted_1[_i];
  21942. item._resyncLighSource(_this);
  21943. }
  21944. return deleted;
  21945. };
  21946. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21947. var item = array_1[_i];
  21948. item._resyncLighSource(this);
  21949. }
  21950. };
  21951. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21952. var _this = this;
  21953. var oldPush = array.push;
  21954. array.push = function () {
  21955. var items = [];
  21956. for (var _i = 0; _i < arguments.length; _i++) {
  21957. items[_i] = arguments[_i];
  21958. }
  21959. var result = oldPush.apply(array, items);
  21960. _this._resyncMeshes();
  21961. return result;
  21962. };
  21963. var oldSplice = array.splice;
  21964. array.splice = function (index, deleteCount) {
  21965. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21966. _this._resyncMeshes();
  21967. return deleted;
  21968. };
  21969. this._resyncMeshes();
  21970. };
  21971. Light.prototype._resyncMeshes = function () {
  21972. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21973. var mesh = _a[_i];
  21974. mesh._resyncLighSource(this);
  21975. }
  21976. };
  21977. /**
  21978. * Forces the meshes to update their light related information in their rendering used effects
  21979. * @hidden Internal Use Only
  21980. */
  21981. Light.prototype._markMeshesAsLightDirty = function () {
  21982. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21983. var mesh = _a[_i];
  21984. if (mesh._lightSources.indexOf(this) !== -1) {
  21985. mesh._markSubMeshesAsLightDirty();
  21986. }
  21987. }
  21988. };
  21989. /**
  21990. * Recomputes the cached photometric scale if needed.
  21991. */
  21992. Light.prototype._computePhotometricScale = function () {
  21993. this._photometricScale = this._getPhotometricScale();
  21994. this.getScene().resetCachedMaterial();
  21995. };
  21996. /**
  21997. * Returns the Photometric Scale according to the light type and intensity mode.
  21998. */
  21999. Light.prototype._getPhotometricScale = function () {
  22000. var photometricScale = 0.0;
  22001. var lightTypeID = this.getTypeID();
  22002. //get photometric mode
  22003. var photometricMode = this.intensityMode;
  22004. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22005. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22006. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22007. }
  22008. else {
  22009. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22010. }
  22011. }
  22012. //compute photometric scale
  22013. switch (lightTypeID) {
  22014. case Light.LIGHTTYPEID_POINTLIGHT:
  22015. case Light.LIGHTTYPEID_SPOTLIGHT:
  22016. switch (photometricMode) {
  22017. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22018. photometricScale = 1.0 / (4.0 * Math.PI);
  22019. break;
  22020. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22021. photometricScale = 1.0;
  22022. break;
  22023. case Light.INTENSITYMODE_LUMINANCE:
  22024. photometricScale = this.radius * this.radius;
  22025. break;
  22026. }
  22027. break;
  22028. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22029. switch (photometricMode) {
  22030. case Light.INTENSITYMODE_ILLUMINANCE:
  22031. photometricScale = 1.0;
  22032. break;
  22033. case Light.INTENSITYMODE_LUMINANCE:
  22034. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22035. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22036. var apexAngleRadians = this.radius;
  22037. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22038. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22039. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22040. photometricScale = solidAngle;
  22041. break;
  22042. }
  22043. break;
  22044. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22045. // No fall off in hemisperic light.
  22046. photometricScale = 1.0;
  22047. break;
  22048. }
  22049. return photometricScale;
  22050. };
  22051. /**
  22052. * Reorder the light in the scene according to their defined priority.
  22053. * @hidden Internal Use Only
  22054. */
  22055. Light.prototype._reorderLightsInScene = function () {
  22056. var scene = this.getScene();
  22057. if (this._renderPriority != 0) {
  22058. scene.requireLightSorting = true;
  22059. }
  22060. this.getScene().sortLightsByPriority();
  22061. };
  22062. //lightmapMode Consts
  22063. Light._LIGHTMAP_DEFAULT = 0;
  22064. Light._LIGHTMAP_SPECULAR = 1;
  22065. Light._LIGHTMAP_SHADOWSONLY = 2;
  22066. // Intensity Mode Consts
  22067. Light._INTENSITYMODE_AUTOMATIC = 0;
  22068. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22069. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22070. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22071. Light._INTENSITYMODE_LUMINANCE = 4;
  22072. // Light types ids const.
  22073. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22074. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22075. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22076. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22077. __decorate([
  22078. BABYLON.serializeAsColor3()
  22079. ], Light.prototype, "diffuse", void 0);
  22080. __decorate([
  22081. BABYLON.serializeAsColor3()
  22082. ], Light.prototype, "specular", void 0);
  22083. __decorate([
  22084. BABYLON.serialize()
  22085. ], Light.prototype, "intensity", void 0);
  22086. __decorate([
  22087. BABYLON.serialize()
  22088. ], Light.prototype, "range", void 0);
  22089. __decorate([
  22090. BABYLON.serialize()
  22091. ], Light.prototype, "intensityMode", null);
  22092. __decorate([
  22093. BABYLON.serialize()
  22094. ], Light.prototype, "radius", null);
  22095. __decorate([
  22096. BABYLON.serialize()
  22097. ], Light.prototype, "_renderPriority", void 0);
  22098. __decorate([
  22099. BABYLON.expandToProperty("_reorderLightsInScene")
  22100. ], Light.prototype, "renderPriority", void 0);
  22101. __decorate([
  22102. BABYLON.serialize("shadowEnabled")
  22103. ], Light.prototype, "_shadowEnabled", void 0);
  22104. __decorate([
  22105. BABYLON.serialize("excludeWithLayerMask")
  22106. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22107. __decorate([
  22108. BABYLON.serialize("includeOnlyWithLayerMask")
  22109. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22110. __decorate([
  22111. BABYLON.serialize("lightmapMode")
  22112. ], Light.prototype, "_lightmapMode", void 0);
  22113. return Light;
  22114. }(BABYLON.Node));
  22115. BABYLON.Light = Light;
  22116. })(BABYLON || (BABYLON = {}));
  22117. //# sourceMappingURL=babylon.light.js.map
  22118. var BABYLON;
  22119. (function (BABYLON) {
  22120. var Camera = /** @class */ (function (_super) {
  22121. __extends(Camera, _super);
  22122. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22123. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22124. var _this = _super.call(this, name, scene) || this;
  22125. /**
  22126. * The vector the camera should consider as up.
  22127. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22128. */
  22129. _this.upVector = BABYLON.Vector3.Up();
  22130. _this.orthoLeft = null;
  22131. _this.orthoRight = null;
  22132. _this.orthoBottom = null;
  22133. _this.orthoTop = null;
  22134. /**
  22135. * FOV is set in Radians. (default is 0.8)
  22136. */
  22137. _this.fov = 0.8;
  22138. _this.minZ = 1;
  22139. _this.maxZ = 10000.0;
  22140. _this.inertia = 0.9;
  22141. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22142. _this.isIntermediate = false;
  22143. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22144. /**
  22145. * Restricts the camera to viewing objects with the same layerMask.
  22146. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22147. */
  22148. _this.layerMask = 0x0FFFFFFF;
  22149. /**
  22150. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22151. */
  22152. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22153. // Camera rig members
  22154. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22155. _this._rigCameras = new Array();
  22156. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22157. _this._skipRendering = false;
  22158. _this.customRenderTargets = new Array();
  22159. // Observables
  22160. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22161. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22162. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22163. _this.onRestoreStateObservable = new BABYLON.Observable();
  22164. // Cache
  22165. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22166. _this._projectionMatrix = new BABYLON.Matrix();
  22167. _this._doNotComputeProjectionMatrix = false;
  22168. _this._worldMatrix = BABYLON.Matrix.Identity();
  22169. _this._postProcesses = new Array();
  22170. _this._transformMatrix = BABYLON.Matrix.Zero();
  22171. _this._activeMeshes = new BABYLON.SmartArray(256);
  22172. _this._globalPosition = BABYLON.Vector3.Zero();
  22173. _this._refreshFrustumPlanes = true;
  22174. _this.getScene().addCamera(_this);
  22175. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22176. _this.getScene().activeCamera = _this;
  22177. }
  22178. _this.position = position;
  22179. return _this;
  22180. }
  22181. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22182. get: function () {
  22183. return Camera._PERSPECTIVE_CAMERA;
  22184. },
  22185. enumerable: true,
  22186. configurable: true
  22187. });
  22188. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22189. get: function () {
  22190. return Camera._ORTHOGRAPHIC_CAMERA;
  22191. },
  22192. enumerable: true,
  22193. configurable: true
  22194. });
  22195. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22196. /**
  22197. * This is the default FOV mode for perspective cameras.
  22198. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22199. *
  22200. */
  22201. get: function () {
  22202. return Camera._FOVMODE_VERTICAL_FIXED;
  22203. },
  22204. enumerable: true,
  22205. configurable: true
  22206. });
  22207. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22208. /**
  22209. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22210. *
  22211. */
  22212. get: function () {
  22213. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22219. get: function () {
  22220. return Camera._RIG_MODE_NONE;
  22221. },
  22222. enumerable: true,
  22223. configurable: true
  22224. });
  22225. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22226. get: function () {
  22227. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22228. },
  22229. enumerable: true,
  22230. configurable: true
  22231. });
  22232. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22233. get: function () {
  22234. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22235. },
  22236. enumerable: true,
  22237. configurable: true
  22238. });
  22239. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22240. get: function () {
  22241. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22242. },
  22243. enumerable: true,
  22244. configurable: true
  22245. });
  22246. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22247. get: function () {
  22248. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22249. },
  22250. enumerable: true,
  22251. configurable: true
  22252. });
  22253. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22254. get: function () {
  22255. return Camera._RIG_MODE_VR;
  22256. },
  22257. enumerable: true,
  22258. configurable: true
  22259. });
  22260. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22261. get: function () {
  22262. return Camera._RIG_MODE_WEBVR;
  22263. },
  22264. enumerable: true,
  22265. configurable: true
  22266. });
  22267. /**
  22268. * Store current camera state (fov, position, etc..)
  22269. */
  22270. Camera.prototype.storeState = function () {
  22271. this._stateStored = true;
  22272. this._storedFov = this.fov;
  22273. return this;
  22274. };
  22275. /**
  22276. * Restores the camera state values if it has been stored. You must call storeState() first
  22277. */
  22278. Camera.prototype._restoreStateValues = function () {
  22279. if (!this._stateStored) {
  22280. return false;
  22281. }
  22282. this.fov = this._storedFov;
  22283. return true;
  22284. };
  22285. /**
  22286. * Restored camera state. You must call storeState() first
  22287. */
  22288. Camera.prototype.restoreState = function () {
  22289. if (this._restoreStateValues()) {
  22290. this.onRestoreStateObservable.notifyObservers(this);
  22291. return true;
  22292. }
  22293. return false;
  22294. };
  22295. Camera.prototype.getClassName = function () {
  22296. return "Camera";
  22297. };
  22298. /**
  22299. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22300. */
  22301. Camera.prototype.toString = function (fullDetails) {
  22302. var ret = "Name: " + this.name;
  22303. ret += ", type: " + this.getClassName();
  22304. if (this.animations) {
  22305. for (var i = 0; i < this.animations.length; i++) {
  22306. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22307. }
  22308. }
  22309. if (fullDetails) {
  22310. }
  22311. return ret;
  22312. };
  22313. Object.defineProperty(Camera.prototype, "globalPosition", {
  22314. get: function () {
  22315. return this._globalPosition;
  22316. },
  22317. enumerable: true,
  22318. configurable: true
  22319. });
  22320. Camera.prototype.getActiveMeshes = function () {
  22321. return this._activeMeshes;
  22322. };
  22323. Camera.prototype.isActiveMesh = function (mesh) {
  22324. return (this._activeMeshes.indexOf(mesh) !== -1);
  22325. };
  22326. /**
  22327. * Is this camera ready to be used/rendered
  22328. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22329. * @return true if the camera is ready
  22330. */
  22331. Camera.prototype.isReady = function (completeCheck) {
  22332. if (completeCheck === void 0) { completeCheck = false; }
  22333. if (completeCheck) {
  22334. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22335. var pp = _a[_i];
  22336. if (pp && !pp.isReady()) {
  22337. return false;
  22338. }
  22339. }
  22340. }
  22341. return _super.prototype.isReady.call(this, completeCheck);
  22342. };
  22343. //Cache
  22344. Camera.prototype._initCache = function () {
  22345. _super.prototype._initCache.call(this);
  22346. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22347. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22348. this._cache.mode = undefined;
  22349. this._cache.minZ = undefined;
  22350. this._cache.maxZ = undefined;
  22351. this._cache.fov = undefined;
  22352. this._cache.fovMode = undefined;
  22353. this._cache.aspectRatio = undefined;
  22354. this._cache.orthoLeft = undefined;
  22355. this._cache.orthoRight = undefined;
  22356. this._cache.orthoBottom = undefined;
  22357. this._cache.orthoTop = undefined;
  22358. this._cache.renderWidth = undefined;
  22359. this._cache.renderHeight = undefined;
  22360. };
  22361. Camera.prototype._updateCache = function (ignoreParentClass) {
  22362. if (!ignoreParentClass) {
  22363. _super.prototype._updateCache.call(this);
  22364. }
  22365. this._cache.position.copyFrom(this.position);
  22366. this._cache.upVector.copyFrom(this.upVector);
  22367. };
  22368. // Synchronized
  22369. Camera.prototype._isSynchronized = function () {
  22370. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22371. };
  22372. Camera.prototype._isSynchronizedViewMatrix = function () {
  22373. if (!_super.prototype._isSynchronized.call(this))
  22374. return false;
  22375. return this._cache.position.equals(this.position)
  22376. && this._cache.upVector.equals(this.upVector)
  22377. && this.isSynchronizedWithParent();
  22378. };
  22379. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22380. var check = this._cache.mode === this.mode
  22381. && this._cache.minZ === this.minZ
  22382. && this._cache.maxZ === this.maxZ;
  22383. if (!check) {
  22384. return false;
  22385. }
  22386. var engine = this.getEngine();
  22387. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22388. check = this._cache.fov === this.fov
  22389. && this._cache.fovMode === this.fovMode
  22390. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22391. }
  22392. else {
  22393. check = this._cache.orthoLeft === this.orthoLeft
  22394. && this._cache.orthoRight === this.orthoRight
  22395. && this._cache.orthoBottom === this.orthoBottom
  22396. && this._cache.orthoTop === this.orthoTop
  22397. && this._cache.renderWidth === engine.getRenderWidth()
  22398. && this._cache.renderHeight === engine.getRenderHeight();
  22399. }
  22400. return check;
  22401. };
  22402. // Controls
  22403. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22404. };
  22405. Camera.prototype.detachControl = function (element) {
  22406. };
  22407. Camera.prototype.update = function () {
  22408. this._checkInputs();
  22409. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22410. this._updateRigCameras();
  22411. }
  22412. };
  22413. Camera.prototype._checkInputs = function () {
  22414. this.onAfterCheckInputsObservable.notifyObservers(this);
  22415. };
  22416. Object.defineProperty(Camera.prototype, "rigCameras", {
  22417. get: function () {
  22418. return this._rigCameras;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22424. get: function () {
  22425. return this._rigPostProcess;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. /**
  22431. * Internal, gets the first post proces.
  22432. * @returns the first post process to be run on this camera.
  22433. */
  22434. Camera.prototype._getFirstPostProcess = function () {
  22435. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22436. if (this._postProcesses[ppIndex] !== null) {
  22437. return this._postProcesses[ppIndex];
  22438. }
  22439. }
  22440. return null;
  22441. };
  22442. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22443. // invalidate framebuffer
  22444. var firstPostProcess = this._getFirstPostProcess();
  22445. if (firstPostProcess) {
  22446. firstPostProcess.markTextureDirty();
  22447. }
  22448. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22449. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22450. var cam = this._rigCameras[i];
  22451. var rigPostProcess = cam._rigPostProcess;
  22452. // for VR rig, there does not have to be a post process
  22453. if (rigPostProcess) {
  22454. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22455. if (isPass) {
  22456. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22457. cam.isIntermediate = this._postProcesses.length === 0;
  22458. }
  22459. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22460. rigPostProcess.markTextureDirty();
  22461. }
  22462. else {
  22463. cam._postProcesses = this._postProcesses.slice(0);
  22464. }
  22465. }
  22466. };
  22467. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22468. if (insertAt === void 0) { insertAt = null; }
  22469. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22470. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22471. return 0;
  22472. }
  22473. if (insertAt == null || insertAt < 0) {
  22474. this._postProcesses.push(postProcess);
  22475. }
  22476. else if (this._postProcesses[insertAt] === null) {
  22477. this._postProcesses[insertAt] = postProcess;
  22478. }
  22479. else {
  22480. this._postProcesses.splice(insertAt, 0, postProcess);
  22481. }
  22482. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22483. return this._postProcesses.indexOf(postProcess);
  22484. };
  22485. Camera.prototype.detachPostProcess = function (postProcess) {
  22486. var idx = this._postProcesses.indexOf(postProcess);
  22487. if (idx !== -1) {
  22488. this._postProcesses[idx] = null;
  22489. }
  22490. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22491. };
  22492. Camera.prototype.getWorldMatrix = function () {
  22493. if (this._isSynchronizedViewMatrix()) {
  22494. return this._worldMatrix;
  22495. }
  22496. // Getting the the view matrix will also compute the world matrix.
  22497. this.getViewMatrix();
  22498. return this._worldMatrix;
  22499. };
  22500. Camera.prototype._getViewMatrix = function () {
  22501. return BABYLON.Matrix.Identity();
  22502. };
  22503. Camera.prototype.getViewMatrix = function (force) {
  22504. if (!force && this._isSynchronizedViewMatrix()) {
  22505. return this._computedViewMatrix;
  22506. }
  22507. this.updateCache();
  22508. this._computedViewMatrix = this._getViewMatrix();
  22509. this._currentRenderId = this.getScene().getRenderId();
  22510. this._childRenderId = this._currentRenderId;
  22511. this._refreshFrustumPlanes = true;
  22512. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22513. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22514. }
  22515. this.onViewMatrixChangedObservable.notifyObservers(this);
  22516. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22517. return this._computedViewMatrix;
  22518. };
  22519. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22520. this._doNotComputeProjectionMatrix = true;
  22521. if (projection !== undefined) {
  22522. this._projectionMatrix = projection;
  22523. }
  22524. };
  22525. ;
  22526. Camera.prototype.unfreezeProjectionMatrix = function () {
  22527. this._doNotComputeProjectionMatrix = false;
  22528. };
  22529. ;
  22530. Camera.prototype.getProjectionMatrix = function (force) {
  22531. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22532. return this._projectionMatrix;
  22533. }
  22534. // Cache
  22535. this._cache.mode = this.mode;
  22536. this._cache.minZ = this.minZ;
  22537. this._cache.maxZ = this.maxZ;
  22538. // Matrix
  22539. this._refreshFrustumPlanes = true;
  22540. var engine = this.getEngine();
  22541. var scene = this.getScene();
  22542. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22543. this._cache.fov = this.fov;
  22544. this._cache.fovMode = this.fovMode;
  22545. this._cache.aspectRatio = engine.getAspectRatio(this);
  22546. if (this.minZ <= 0) {
  22547. this.minZ = 0.1;
  22548. }
  22549. if (scene.useRightHandedSystem) {
  22550. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22551. }
  22552. else {
  22553. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22554. }
  22555. }
  22556. else {
  22557. var halfWidth = engine.getRenderWidth() / 2.0;
  22558. var halfHeight = engine.getRenderHeight() / 2.0;
  22559. if (scene.useRightHandedSystem) {
  22560. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22561. }
  22562. else {
  22563. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22564. }
  22565. this._cache.orthoLeft = this.orthoLeft;
  22566. this._cache.orthoRight = this.orthoRight;
  22567. this._cache.orthoBottom = this.orthoBottom;
  22568. this._cache.orthoTop = this.orthoTop;
  22569. this._cache.renderWidth = engine.getRenderWidth();
  22570. this._cache.renderHeight = engine.getRenderHeight();
  22571. }
  22572. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22573. return this._projectionMatrix;
  22574. };
  22575. Camera.prototype.getTranformationMatrix = function () {
  22576. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22577. return this._transformMatrix;
  22578. };
  22579. Camera.prototype.updateFrustumPlanes = function () {
  22580. if (!this._refreshFrustumPlanes) {
  22581. return;
  22582. }
  22583. this.getTranformationMatrix();
  22584. if (!this._frustumPlanes) {
  22585. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22586. }
  22587. else {
  22588. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22589. }
  22590. this._refreshFrustumPlanes = false;
  22591. };
  22592. Camera.prototype.isInFrustum = function (target) {
  22593. this.updateFrustumPlanes();
  22594. return target.isInFrustum(this._frustumPlanes);
  22595. };
  22596. Camera.prototype.isCompletelyInFrustum = function (target) {
  22597. this.updateFrustumPlanes();
  22598. return target.isCompletelyInFrustum(this._frustumPlanes);
  22599. };
  22600. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22601. if (length === void 0) { length = 100; }
  22602. if (!transform) {
  22603. transform = this.getWorldMatrix();
  22604. }
  22605. if (!origin) {
  22606. origin = this.position;
  22607. }
  22608. var forward = new BABYLON.Vector3(0, 0, 1);
  22609. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22610. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22611. return new BABYLON.Ray(origin, direction, length);
  22612. };
  22613. /**
  22614. * Releases resources associated with this node.
  22615. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22616. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22617. */
  22618. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22619. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22620. // Observables
  22621. this.onViewMatrixChangedObservable.clear();
  22622. this.onProjectionMatrixChangedObservable.clear();
  22623. this.onAfterCheckInputsObservable.clear();
  22624. this.onRestoreStateObservable.clear();
  22625. // Inputs
  22626. if (this.inputs) {
  22627. this.inputs.clear();
  22628. }
  22629. // Animations
  22630. this.getScene().stopAnimation(this);
  22631. // Remove from scene
  22632. this.getScene().removeCamera(this);
  22633. while (this._rigCameras.length > 0) {
  22634. var camera = this._rigCameras.pop();
  22635. if (camera) {
  22636. camera.dispose();
  22637. }
  22638. }
  22639. // Postprocesses
  22640. if (this._rigPostProcess) {
  22641. this._rigPostProcess.dispose(this);
  22642. this._rigPostProcess = null;
  22643. this._postProcesses = [];
  22644. }
  22645. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22646. this._rigPostProcess = null;
  22647. this._postProcesses = [];
  22648. }
  22649. else {
  22650. var i = this._postProcesses.length;
  22651. while (--i >= 0) {
  22652. var postProcess = this._postProcesses[i];
  22653. if (postProcess) {
  22654. postProcess.dispose(this);
  22655. }
  22656. }
  22657. }
  22658. // Render targets
  22659. var i = this.customRenderTargets.length;
  22660. while (--i >= 0) {
  22661. this.customRenderTargets[i].dispose();
  22662. }
  22663. this.customRenderTargets = [];
  22664. // Active Meshes
  22665. this._activeMeshes.dispose();
  22666. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22667. };
  22668. Object.defineProperty(Camera.prototype, "leftCamera", {
  22669. // ---- Camera rigs section ----
  22670. get: function () {
  22671. if (this._rigCameras.length < 1) {
  22672. return null;
  22673. }
  22674. return this._rigCameras[0];
  22675. },
  22676. enumerable: true,
  22677. configurable: true
  22678. });
  22679. Object.defineProperty(Camera.prototype, "rightCamera", {
  22680. get: function () {
  22681. if (this._rigCameras.length < 2) {
  22682. return null;
  22683. }
  22684. return this._rigCameras[1];
  22685. },
  22686. enumerable: true,
  22687. configurable: true
  22688. });
  22689. Camera.prototype.getLeftTarget = function () {
  22690. if (this._rigCameras.length < 1) {
  22691. return null;
  22692. }
  22693. return this._rigCameras[0].getTarget();
  22694. };
  22695. Camera.prototype.getRightTarget = function () {
  22696. if (this._rigCameras.length < 2) {
  22697. return null;
  22698. }
  22699. return this._rigCameras[1].getTarget();
  22700. };
  22701. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22702. if (this.cameraRigMode === mode) {
  22703. return;
  22704. }
  22705. while (this._rigCameras.length > 0) {
  22706. var camera = this._rigCameras.pop();
  22707. if (camera) {
  22708. camera.dispose();
  22709. }
  22710. }
  22711. this.cameraRigMode = mode;
  22712. this._cameraRigParams = {};
  22713. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22714. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22715. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22716. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22717. // create the rig cameras, unless none
  22718. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22719. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22720. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22721. if (leftCamera && rightCamera) {
  22722. this._rigCameras.push(leftCamera);
  22723. this._rigCameras.push(rightCamera);
  22724. }
  22725. }
  22726. switch (this.cameraRigMode) {
  22727. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22728. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22729. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22730. break;
  22731. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22732. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22733. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22734. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22735. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22736. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22737. break;
  22738. case Camera.RIG_MODE_VR:
  22739. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22740. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22741. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22742. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22743. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22744. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22745. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22746. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22747. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22748. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22749. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22750. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22751. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22752. if (metrics.compensateDistortion) {
  22753. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22754. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22755. }
  22756. break;
  22757. case Camera.RIG_MODE_WEBVR:
  22758. if (rigParams.vrDisplay) {
  22759. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22760. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22761. //Left eye
  22762. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22763. this._rigCameras[0].setCameraRigParameter("left", true);
  22764. //leaving this for future reference
  22765. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22766. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22767. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22768. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22769. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22770. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22771. this._rigCameras[0].parent = this;
  22772. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22773. //Right eye
  22774. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22775. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22776. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22777. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22778. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22779. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22780. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22781. this._rigCameras[1].parent = this;
  22782. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22783. if (Camera.UseAlternateWebVRRendering) {
  22784. this._rigCameras[1]._skipRendering = true;
  22785. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22786. }
  22787. }
  22788. break;
  22789. }
  22790. this._cascadePostProcessesToRigCams();
  22791. this.update();
  22792. };
  22793. Camera.prototype._getVRProjectionMatrix = function () {
  22794. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22795. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22796. return this._projectionMatrix;
  22797. };
  22798. Camera.prototype._updateCameraRotationMatrix = function () {
  22799. //Here for WebVR
  22800. };
  22801. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22802. //Here for WebVR
  22803. };
  22804. /**
  22805. * This function MUST be overwritten by the different WebVR cameras available.
  22806. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22807. */
  22808. Camera.prototype._getWebVRProjectionMatrix = function () {
  22809. return BABYLON.Matrix.Identity();
  22810. };
  22811. /**
  22812. * This function MUST be overwritten by the different WebVR cameras available.
  22813. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22814. */
  22815. Camera.prototype._getWebVRViewMatrix = function () {
  22816. return BABYLON.Matrix.Identity();
  22817. };
  22818. Camera.prototype.setCameraRigParameter = function (name, value) {
  22819. if (!this._cameraRigParams) {
  22820. this._cameraRigParams = {};
  22821. }
  22822. this._cameraRigParams[name] = value;
  22823. //provisionnally:
  22824. if (name === "interaxialDistance") {
  22825. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22826. }
  22827. };
  22828. /**
  22829. * needs to be overridden by children so sub has required properties to be copied
  22830. */
  22831. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22832. return null;
  22833. };
  22834. /**
  22835. * May need to be overridden by children
  22836. */
  22837. Camera.prototype._updateRigCameras = function () {
  22838. for (var i = 0; i < this._rigCameras.length; i++) {
  22839. this._rigCameras[i].minZ = this.minZ;
  22840. this._rigCameras[i].maxZ = this.maxZ;
  22841. this._rigCameras[i].fov = this.fov;
  22842. }
  22843. // only update viewport when ANAGLYPH
  22844. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22845. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22846. }
  22847. };
  22848. Camera.prototype._setupInputs = function () {
  22849. };
  22850. Camera.prototype.serialize = function () {
  22851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22852. // Type
  22853. serializationObject.type = this.getClassName();
  22854. // Parent
  22855. if (this.parent) {
  22856. serializationObject.parentId = this.parent.id;
  22857. }
  22858. if (this.inputs) {
  22859. this.inputs.serialize(serializationObject);
  22860. }
  22861. // Animations
  22862. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22863. serializationObject.ranges = this.serializeAnimationRanges();
  22864. return serializationObject;
  22865. };
  22866. Camera.prototype.clone = function (name) {
  22867. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22868. };
  22869. Camera.prototype.getDirection = function (localAxis) {
  22870. var result = BABYLON.Vector3.Zero();
  22871. this.getDirectionToRef(localAxis, result);
  22872. return result;
  22873. };
  22874. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22875. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22876. };
  22877. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22878. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22879. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22880. switch (type) {
  22881. case "ArcRotateCamera":
  22882. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22883. case "DeviceOrientationCamera":
  22884. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22885. case "FollowCamera":
  22886. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22887. case "ArcFollowCamera":
  22888. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22889. case "GamepadCamera":
  22890. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22891. case "TouchCamera":
  22892. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22893. case "VirtualJoysticksCamera":
  22894. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22895. case "WebVRFreeCamera":
  22896. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22897. case "WebVRGamepadCamera":
  22898. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22899. case "VRDeviceOrientationFreeCamera":
  22900. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22901. case "VRDeviceOrientationGamepadCamera":
  22902. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22903. case "AnaglyphArcRotateCamera":
  22904. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22905. case "AnaglyphFreeCamera":
  22906. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22907. case "AnaglyphGamepadCamera":
  22908. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22909. case "AnaglyphUniversalCamera":
  22910. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22911. case "StereoscopicArcRotateCamera":
  22912. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22913. case "StereoscopicFreeCamera":
  22914. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22915. case "StereoscopicGamepadCamera":
  22916. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22917. case "StereoscopicUniversalCamera":
  22918. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22919. case "FreeCamera": // Forcing Universal here
  22920. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22921. default: // Universal Camera is the default value
  22922. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22923. }
  22924. };
  22925. Camera.prototype.computeWorldMatrix = function () {
  22926. return this.getWorldMatrix();
  22927. };
  22928. Camera.Parse = function (parsedCamera, scene) {
  22929. var type = parsedCamera.type;
  22930. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22931. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22932. // Parent
  22933. if (parsedCamera.parentId) {
  22934. camera._waitingParentId = parsedCamera.parentId;
  22935. }
  22936. //If camera has an input manager, let it parse inputs settings
  22937. if (camera.inputs) {
  22938. camera.inputs.parse(parsedCamera);
  22939. camera._setupInputs();
  22940. }
  22941. if (camera.setPosition) { // need to force position
  22942. camera.position.copyFromFloats(0, 0, 0);
  22943. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22944. }
  22945. // Target
  22946. if (parsedCamera.target) {
  22947. if (camera.setTarget) {
  22948. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22949. }
  22950. }
  22951. // Apply 3d rig, when found
  22952. if (parsedCamera.cameraRigMode) {
  22953. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22954. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22955. }
  22956. // Animations
  22957. if (parsedCamera.animations) {
  22958. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22959. var parsedAnimation = parsedCamera.animations[animationIndex];
  22960. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22961. }
  22962. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22963. }
  22964. if (parsedCamera.autoAnimate) {
  22965. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22966. }
  22967. return camera;
  22968. };
  22969. // Statics
  22970. Camera._PERSPECTIVE_CAMERA = 0;
  22971. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22972. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22973. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22974. Camera._RIG_MODE_NONE = 0;
  22975. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22976. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22977. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22978. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22979. Camera._RIG_MODE_VR = 20;
  22980. Camera._RIG_MODE_WEBVR = 21;
  22981. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22982. Camera.UseAlternateWebVRRendering = false;
  22983. __decorate([
  22984. BABYLON.serializeAsVector3()
  22985. ], Camera.prototype, "position", void 0);
  22986. __decorate([
  22987. BABYLON.serializeAsVector3()
  22988. ], Camera.prototype, "upVector", void 0);
  22989. __decorate([
  22990. BABYLON.serialize()
  22991. ], Camera.prototype, "orthoLeft", void 0);
  22992. __decorate([
  22993. BABYLON.serialize()
  22994. ], Camera.prototype, "orthoRight", void 0);
  22995. __decorate([
  22996. BABYLON.serialize()
  22997. ], Camera.prototype, "orthoBottom", void 0);
  22998. __decorate([
  22999. BABYLON.serialize()
  23000. ], Camera.prototype, "orthoTop", void 0);
  23001. __decorate([
  23002. BABYLON.serialize()
  23003. ], Camera.prototype, "fov", void 0);
  23004. __decorate([
  23005. BABYLON.serialize()
  23006. ], Camera.prototype, "minZ", void 0);
  23007. __decorate([
  23008. BABYLON.serialize()
  23009. ], Camera.prototype, "maxZ", void 0);
  23010. __decorate([
  23011. BABYLON.serialize()
  23012. ], Camera.prototype, "inertia", void 0);
  23013. __decorate([
  23014. BABYLON.serialize()
  23015. ], Camera.prototype, "mode", void 0);
  23016. __decorate([
  23017. BABYLON.serialize()
  23018. ], Camera.prototype, "layerMask", void 0);
  23019. __decorate([
  23020. BABYLON.serialize()
  23021. ], Camera.prototype, "fovMode", void 0);
  23022. __decorate([
  23023. BABYLON.serialize()
  23024. ], Camera.prototype, "cameraRigMode", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], Camera.prototype, "interaxialDistance", void 0);
  23028. __decorate([
  23029. BABYLON.serialize()
  23030. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23031. return Camera;
  23032. }(BABYLON.Node));
  23033. BABYLON.Camera = Camera;
  23034. })(BABYLON || (BABYLON = {}));
  23035. //# sourceMappingURL=babylon.camera.js.map
  23036. var BABYLON;
  23037. (function (BABYLON) {
  23038. var RenderingManager = /** @class */ (function () {
  23039. function RenderingManager(scene) {
  23040. this._renderingGroups = new Array();
  23041. this._autoClearDepthStencil = {};
  23042. this._customOpaqueSortCompareFn = {};
  23043. this._customAlphaTestSortCompareFn = {};
  23044. this._customTransparentSortCompareFn = {};
  23045. this._renderinGroupInfo = null;
  23046. this._scene = scene;
  23047. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23048. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23049. }
  23050. }
  23051. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23052. if (depth === void 0) { depth = true; }
  23053. if (stencil === void 0) { stencil = true; }
  23054. if (this._depthStencilBufferAlreadyCleaned) {
  23055. return;
  23056. }
  23057. this._scene.getEngine().clear(null, false, depth, stencil);
  23058. this._depthStencilBufferAlreadyCleaned = true;
  23059. };
  23060. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23061. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23062. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23063. var info = null;
  23064. if (observable) {
  23065. if (!this._renderinGroupInfo) {
  23066. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23067. }
  23068. info = this._renderinGroupInfo;
  23069. info.scene = this._scene;
  23070. info.camera = this._scene.activeCamera;
  23071. }
  23072. // Dispatch sprites
  23073. if (renderSprites) {
  23074. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23075. var manager = this._scene.spriteManagers[index];
  23076. this.dispatchSprites(manager);
  23077. }
  23078. }
  23079. // Render
  23080. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23081. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23082. var renderingGroup = this._renderingGroups[index];
  23083. if (!renderingGroup && !observable)
  23084. continue;
  23085. var renderingGroupMask = 0;
  23086. // Fire PRECLEAR stage
  23087. if (observable && info) {
  23088. renderingGroupMask = Math.pow(2, index);
  23089. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23090. info.renderingGroupId = index;
  23091. observable.notifyObservers(info, renderingGroupMask);
  23092. }
  23093. // Clear depth/stencil if needed
  23094. if (RenderingManager.AUTOCLEAR) {
  23095. var autoClear = this._autoClearDepthStencil[index];
  23096. if (autoClear && autoClear.autoClear) {
  23097. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23098. }
  23099. }
  23100. if (observable && info) {
  23101. // Fire PREOPAQUE stage
  23102. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23103. observable.notifyObservers(info, renderingGroupMask);
  23104. // Fire PRETRANSPARENT stage
  23105. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23106. observable.notifyObservers(info, renderingGroupMask);
  23107. }
  23108. if (renderingGroup)
  23109. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23110. // Fire POSTTRANSPARENT stage
  23111. if (observable && info) {
  23112. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23113. observable.notifyObservers(info, renderingGroupMask);
  23114. }
  23115. }
  23116. };
  23117. RenderingManager.prototype.reset = function () {
  23118. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23119. var renderingGroup = this._renderingGroups[index];
  23120. if (renderingGroup) {
  23121. renderingGroup.prepare();
  23122. }
  23123. }
  23124. };
  23125. RenderingManager.prototype.dispose = function () {
  23126. this.freeRenderingGroups();
  23127. this._renderingGroups.length = 0;
  23128. };
  23129. /**
  23130. * Clear the info related to rendering groups preventing retention points during dispose.
  23131. */
  23132. RenderingManager.prototype.freeRenderingGroups = function () {
  23133. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23134. var renderingGroup = this._renderingGroups[index];
  23135. if (renderingGroup) {
  23136. renderingGroup.dispose();
  23137. }
  23138. }
  23139. };
  23140. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23141. if (this._renderingGroups[renderingGroupId] === undefined) {
  23142. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23143. }
  23144. };
  23145. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23146. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23147. this._prepareRenderingGroup(renderingGroupId);
  23148. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23149. };
  23150. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23151. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23152. this._prepareRenderingGroup(renderingGroupId);
  23153. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23154. };
  23155. /**
  23156. * @param subMesh The submesh to dispatch
  23157. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23158. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23159. */
  23160. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23161. if (mesh === undefined) {
  23162. mesh = subMesh.getMesh();
  23163. }
  23164. var renderingGroupId = mesh.renderingGroupId || 0;
  23165. this._prepareRenderingGroup(renderingGroupId);
  23166. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23167. };
  23168. /**
  23169. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23170. * This allowed control for front to back rendering or reversly depending of the special needs.
  23171. *
  23172. * @param renderingGroupId The rendering group id corresponding to its index
  23173. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23174. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23175. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23176. */
  23177. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23178. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23179. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23180. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23181. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23182. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23183. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23184. if (this._renderingGroups[renderingGroupId]) {
  23185. var group = this._renderingGroups[renderingGroupId];
  23186. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23187. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23188. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23189. }
  23190. };
  23191. /**
  23192. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23193. *
  23194. * @param renderingGroupId The rendering group id corresponding to its index
  23195. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23196. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23197. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23198. */
  23199. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23200. if (depth === void 0) { depth = true; }
  23201. if (stencil === void 0) { stencil = true; }
  23202. this._autoClearDepthStencil[renderingGroupId] = {
  23203. autoClear: autoClearDepthStencil,
  23204. depth: depth,
  23205. stencil: stencil
  23206. };
  23207. };
  23208. /**
  23209. * The max id used for rendering groups (not included)
  23210. */
  23211. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23212. /**
  23213. * The min id used for rendering groups (included)
  23214. */
  23215. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23216. /**
  23217. * Used to globally prevent autoclearing scenes.
  23218. */
  23219. RenderingManager.AUTOCLEAR = true;
  23220. return RenderingManager;
  23221. }());
  23222. BABYLON.RenderingManager = RenderingManager;
  23223. })(BABYLON || (BABYLON = {}));
  23224. //# sourceMappingURL=babylon.renderingManager.js.map
  23225. var BABYLON;
  23226. (function (BABYLON) {
  23227. var RenderingGroup = /** @class */ (function () {
  23228. /**
  23229. * Creates a new rendering group.
  23230. * @param index The rendering group index
  23231. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23232. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23233. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23234. */
  23235. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23236. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23237. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23238. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23239. this.index = index;
  23240. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23241. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23242. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23243. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23244. this._particleSystems = new BABYLON.SmartArray(256);
  23245. this._spriteManagers = new BABYLON.SmartArray(256);
  23246. this._edgesRenderers = new BABYLON.SmartArray(16);
  23247. this._scene = scene;
  23248. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23249. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23250. this.transparentSortCompareFn = transparentSortCompareFn;
  23251. }
  23252. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23253. /**
  23254. * Set the opaque sort comparison function.
  23255. * If null the sub meshes will be render in the order they were created
  23256. */
  23257. set: function (value) {
  23258. this._opaqueSortCompareFn = value;
  23259. if (value) {
  23260. this._renderOpaque = this.renderOpaqueSorted;
  23261. }
  23262. else {
  23263. this._renderOpaque = RenderingGroup.renderUnsorted;
  23264. }
  23265. },
  23266. enumerable: true,
  23267. configurable: true
  23268. });
  23269. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23270. /**
  23271. * Set the alpha test sort comparison function.
  23272. * If null the sub meshes will be render in the order they were created
  23273. */
  23274. set: function (value) {
  23275. this._alphaTestSortCompareFn = value;
  23276. if (value) {
  23277. this._renderAlphaTest = this.renderAlphaTestSorted;
  23278. }
  23279. else {
  23280. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23281. }
  23282. },
  23283. enumerable: true,
  23284. configurable: true
  23285. });
  23286. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23287. /**
  23288. * Set the transparent sort comparison function.
  23289. * If null the sub meshes will be render in the order they were created
  23290. */
  23291. set: function (value) {
  23292. if (value) {
  23293. this._transparentSortCompareFn = value;
  23294. }
  23295. else {
  23296. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23297. }
  23298. this._renderTransparent = this.renderTransparentSorted;
  23299. },
  23300. enumerable: true,
  23301. configurable: true
  23302. });
  23303. /**
  23304. * Render all the sub meshes contained in the group.
  23305. * @param customRenderFunction Used to override the default render behaviour of the group.
  23306. * @returns true if rendered some submeshes.
  23307. */
  23308. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23309. if (customRenderFunction) {
  23310. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23311. return;
  23312. }
  23313. var engine = this._scene.getEngine();
  23314. // Depth only
  23315. if (this._depthOnlySubMeshes.length !== 0) {
  23316. engine.setColorWrite(false);
  23317. this._renderAlphaTest(this._depthOnlySubMeshes);
  23318. engine.setColorWrite(true);
  23319. }
  23320. // Opaque
  23321. if (this._opaqueSubMeshes.length !== 0) {
  23322. this._renderOpaque(this._opaqueSubMeshes);
  23323. }
  23324. // Alpha test
  23325. if (this._alphaTestSubMeshes.length !== 0) {
  23326. this._renderAlphaTest(this._alphaTestSubMeshes);
  23327. }
  23328. var stencilState = engine.getStencilBuffer();
  23329. engine.setStencilBuffer(false);
  23330. // Sprites
  23331. if (renderSprites) {
  23332. this._renderSprites();
  23333. }
  23334. // Particles
  23335. if (renderParticles) {
  23336. this._renderParticles(activeMeshes);
  23337. }
  23338. if (this.onBeforeTransparentRendering) {
  23339. this.onBeforeTransparentRendering();
  23340. }
  23341. // Transparent
  23342. if (this._transparentSubMeshes.length !== 0) {
  23343. this._renderTransparent(this._transparentSubMeshes);
  23344. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23345. }
  23346. // Set back stencil to false in case it changes before the edge renderer.
  23347. engine.setStencilBuffer(false);
  23348. // Edges
  23349. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23350. this._edgesRenderers.data[edgesRendererIndex].render();
  23351. }
  23352. // Restore Stencil state.
  23353. engine.setStencilBuffer(stencilState);
  23354. };
  23355. /**
  23356. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23357. * @param subMeshes The submeshes to render
  23358. */
  23359. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23360. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23361. };
  23362. /**
  23363. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23364. * @param subMeshes The submeshes to render
  23365. */
  23366. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23367. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23368. };
  23369. /**
  23370. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23371. * @param subMeshes The submeshes to render
  23372. */
  23373. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23374. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23375. };
  23376. /**
  23377. * Renders the submeshes in a specified order.
  23378. * @param subMeshes The submeshes to sort before render
  23379. * @param sortCompareFn The comparison function use to sort
  23380. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23381. * @param transparent Specifies to activate blending if true
  23382. */
  23383. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23384. var subIndex = 0;
  23385. var subMesh;
  23386. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23387. for (; subIndex < subMeshes.length; subIndex++) {
  23388. subMesh = subMeshes.data[subIndex];
  23389. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23390. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23391. }
  23392. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23393. if (sortCompareFn) {
  23394. sortedArray.sort(sortCompareFn);
  23395. }
  23396. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23397. subMesh = sortedArray[subIndex];
  23398. if (transparent) {
  23399. var material = subMesh.getMaterial();
  23400. if (material && material.needDepthPrePass) {
  23401. var engine = material.getScene().getEngine();
  23402. engine.setColorWrite(false);
  23403. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23404. subMesh.render(false);
  23405. engine.setColorWrite(true);
  23406. }
  23407. }
  23408. subMesh.render(transparent);
  23409. }
  23410. };
  23411. /**
  23412. * Renders the submeshes in the order they were dispatched (no sort applied).
  23413. * @param subMeshes The submeshes to render
  23414. */
  23415. RenderingGroup.renderUnsorted = function (subMeshes) {
  23416. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23417. var submesh = subMeshes.data[subIndex];
  23418. submesh.render(false);
  23419. }
  23420. };
  23421. /**
  23422. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23423. * are rendered back to front if in the same alpha index.
  23424. *
  23425. * @param a The first submesh
  23426. * @param b The second submesh
  23427. * @returns The result of the comparison
  23428. */
  23429. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23430. // Alpha index first
  23431. if (a._alphaIndex > b._alphaIndex) {
  23432. return 1;
  23433. }
  23434. if (a._alphaIndex < b._alphaIndex) {
  23435. return -1;
  23436. }
  23437. // Then distance to camera
  23438. return RenderingGroup.backToFrontSortCompare(a, b);
  23439. };
  23440. /**
  23441. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23442. * are rendered back to front.
  23443. *
  23444. * @param a The first submesh
  23445. * @param b The second submesh
  23446. * @returns The result of the comparison
  23447. */
  23448. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23449. // Then distance to camera
  23450. if (a._distanceToCamera < b._distanceToCamera) {
  23451. return 1;
  23452. }
  23453. if (a._distanceToCamera > b._distanceToCamera) {
  23454. return -1;
  23455. }
  23456. return 0;
  23457. };
  23458. /**
  23459. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23460. * are rendered front to back (prevent overdraw).
  23461. *
  23462. * @param a The first submesh
  23463. * @param b The second submesh
  23464. * @returns The result of the comparison
  23465. */
  23466. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23467. // Then distance to camera
  23468. if (a._distanceToCamera < b._distanceToCamera) {
  23469. return -1;
  23470. }
  23471. if (a._distanceToCamera > b._distanceToCamera) {
  23472. return 1;
  23473. }
  23474. return 0;
  23475. };
  23476. /**
  23477. * Resets the different lists of submeshes to prepare a new frame.
  23478. */
  23479. RenderingGroup.prototype.prepare = function () {
  23480. this._opaqueSubMeshes.reset();
  23481. this._transparentSubMeshes.reset();
  23482. this._alphaTestSubMeshes.reset();
  23483. this._depthOnlySubMeshes.reset();
  23484. this._particleSystems.reset();
  23485. this._spriteManagers.reset();
  23486. this._edgesRenderers.reset();
  23487. };
  23488. RenderingGroup.prototype.dispose = function () {
  23489. this._opaqueSubMeshes.dispose();
  23490. this._transparentSubMeshes.dispose();
  23491. this._alphaTestSubMeshes.dispose();
  23492. this._depthOnlySubMeshes.dispose();
  23493. this._particleSystems.dispose();
  23494. this._spriteManagers.dispose();
  23495. this._edgesRenderers.dispose();
  23496. };
  23497. /**
  23498. * Inserts the submesh in its correct queue depending on its material.
  23499. * @param subMesh The submesh to dispatch
  23500. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23501. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23502. */
  23503. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23504. // Get mesh and materials if not provided
  23505. if (mesh === undefined) {
  23506. mesh = subMesh.getMesh();
  23507. }
  23508. if (material === undefined) {
  23509. material = subMesh.getMaterial();
  23510. }
  23511. if (material === null || material === undefined) {
  23512. return;
  23513. }
  23514. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23515. this._transparentSubMeshes.push(subMesh);
  23516. }
  23517. else if (material.needAlphaTesting()) { // Alpha test
  23518. if (material.needDepthPrePass) {
  23519. this._depthOnlySubMeshes.push(subMesh);
  23520. }
  23521. this._alphaTestSubMeshes.push(subMesh);
  23522. }
  23523. else {
  23524. if (material.needDepthPrePass) {
  23525. this._depthOnlySubMeshes.push(subMesh);
  23526. }
  23527. this._opaqueSubMeshes.push(subMesh); // Opaque
  23528. }
  23529. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23530. this._edgesRenderers.push(mesh._edgesRenderer);
  23531. }
  23532. };
  23533. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23534. this._spriteManagers.push(spriteManager);
  23535. };
  23536. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23537. this._particleSystems.push(particleSystem);
  23538. };
  23539. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23540. if (this._particleSystems.length === 0) {
  23541. return;
  23542. }
  23543. // Particles
  23544. var activeCamera = this._scene.activeCamera;
  23545. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23546. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23547. var particleSystem = this._particleSystems.data[particleIndex];
  23548. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23549. continue;
  23550. }
  23551. var emitter = particleSystem.emitter;
  23552. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23553. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23554. }
  23555. }
  23556. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23557. };
  23558. RenderingGroup.prototype._renderSprites = function () {
  23559. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23560. return;
  23561. }
  23562. // Sprites
  23563. var activeCamera = this._scene.activeCamera;
  23564. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23565. for (var id = 0; id < this._spriteManagers.length; id++) {
  23566. var spriteManager = this._spriteManagers.data[id];
  23567. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23568. spriteManager.render();
  23569. }
  23570. }
  23571. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23572. };
  23573. return RenderingGroup;
  23574. }());
  23575. BABYLON.RenderingGroup = RenderingGroup;
  23576. })(BABYLON || (BABYLON = {}));
  23577. //# sourceMappingURL=babylon.renderingGroup.js.map
  23578. var BABYLON;
  23579. (function (BABYLON) {
  23580. /** @hidden */
  23581. var ClickInfo = /** @class */ (function () {
  23582. function ClickInfo() {
  23583. this._singleClick = false;
  23584. this._doubleClick = false;
  23585. this._hasSwiped = false;
  23586. this._ignore = false;
  23587. }
  23588. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23589. get: function () {
  23590. return this._singleClick;
  23591. },
  23592. set: function (b) {
  23593. this._singleClick = b;
  23594. },
  23595. enumerable: true,
  23596. configurable: true
  23597. });
  23598. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23599. get: function () {
  23600. return this._doubleClick;
  23601. },
  23602. set: function (b) {
  23603. this._doubleClick = b;
  23604. },
  23605. enumerable: true,
  23606. configurable: true
  23607. });
  23608. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23609. get: function () {
  23610. return this._hasSwiped;
  23611. },
  23612. set: function (b) {
  23613. this._hasSwiped = b;
  23614. },
  23615. enumerable: true,
  23616. configurable: true
  23617. });
  23618. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23619. get: function () {
  23620. return this._ignore;
  23621. },
  23622. set: function (b) {
  23623. this._ignore = b;
  23624. },
  23625. enumerable: true,
  23626. configurable: true
  23627. });
  23628. return ClickInfo;
  23629. }());
  23630. /**
  23631. * This class is used by the onRenderingGroupObservable
  23632. */
  23633. var RenderingGroupInfo = /** @class */ (function () {
  23634. function RenderingGroupInfo() {
  23635. }
  23636. /**
  23637. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23638. * This stage will be fired no matter what
  23639. */
  23640. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23641. /**
  23642. * Called before opaque object are rendered.
  23643. * This stage will be fired only if there's 3D Opaque content to render
  23644. */
  23645. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23646. /**
  23647. * Called after the opaque objects are rendered and before the transparent ones
  23648. * This stage will be fired only if there's 3D transparent content to render
  23649. */
  23650. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23651. /**
  23652. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23653. * This stage will be fired no matter what
  23654. */
  23655. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23656. return RenderingGroupInfo;
  23657. }());
  23658. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23659. /**
  23660. * Represents a scene to be rendered by the engine.
  23661. * @see http://doc.babylonjs.com/features/scene
  23662. */
  23663. var Scene = /** @class */ (function () {
  23664. /**
  23665. * Creates a new Scene
  23666. * @param engine defines the engine to use to render this scene
  23667. */
  23668. function Scene(engine) {
  23669. // Members
  23670. /**
  23671. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23672. */
  23673. this.autoClear = true;
  23674. /**
  23675. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23676. */
  23677. this.autoClearDepthAndStencil = true;
  23678. /**
  23679. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23680. */
  23681. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23682. /**
  23683. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23684. */
  23685. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23686. this._forceWireframe = false;
  23687. this._forcePointsCloud = false;
  23688. /**
  23689. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23690. */
  23691. this.forceShowBoundingBoxes = false;
  23692. /**
  23693. * Gets or sets a boolean indicating if animations are enabled
  23694. */
  23695. this.animationsEnabled = true;
  23696. this._animationPropertiesOverride = null;
  23697. /**
  23698. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23699. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23700. */
  23701. this.useConstantAnimationDeltaTime = false;
  23702. /**
  23703. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23704. * Please note that it requires to run a ray cast through the scene on every frame
  23705. */
  23706. this.constantlyUpdateMeshUnderPointer = false;
  23707. /**
  23708. * Defines the HTML cursor to use when hovering over interactive elements
  23709. */
  23710. this.hoverCursor = "pointer";
  23711. /**
  23712. * Defines the HTML default cursor to use (empty by default)
  23713. */
  23714. this.defaultCursor = "";
  23715. /**
  23716. * This is used to call preventDefault() on pointer down
  23717. * in order to block unwanted artifacts like system double clicks
  23718. */
  23719. this.preventDefaultOnPointerDown = true;
  23720. // Metadata
  23721. /**
  23722. * Gets or sets user defined metadata
  23723. */
  23724. this.metadata = null;
  23725. /**
  23726. * Use this array to add regular expressions used to disable offline support for specific urls
  23727. */
  23728. this.disableOfflineSupportExceptionRules = new Array();
  23729. /**
  23730. * An event triggered when the scene is disposed.
  23731. */
  23732. this.onDisposeObservable = new BABYLON.Observable();
  23733. this._onDisposeObserver = null;
  23734. /**
  23735. * An event triggered before rendering the scene (right after animations and physics)
  23736. */
  23737. this.onBeforeRenderObservable = new BABYLON.Observable();
  23738. this._onBeforeRenderObserver = null;
  23739. /**
  23740. * An event triggered after rendering the scene
  23741. */
  23742. this.onAfterRenderObservable = new BABYLON.Observable();
  23743. this._onAfterRenderObserver = null;
  23744. /**
  23745. * An event triggered before animating the scene
  23746. */
  23747. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered after animations processing
  23750. */
  23751. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered before draw calls are ready to be sent
  23754. */
  23755. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered after draw calls have been sent
  23758. */
  23759. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered when physic simulation is about to be run
  23762. */
  23763. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23764. /**
  23765. * An event triggered when physic simulation has been done
  23766. */
  23767. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23768. /**
  23769. * An event triggered when the scene is ready
  23770. */
  23771. this.onReadyObservable = new BABYLON.Observable();
  23772. /**
  23773. * An event triggered before rendering a camera
  23774. */
  23775. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23776. this._onBeforeCameraRenderObserver = null;
  23777. /**
  23778. * An event triggered after rendering a camera
  23779. */
  23780. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23781. this._onAfterCameraRenderObserver = null;
  23782. /**
  23783. * An event triggered when active meshes evaluation is about to start
  23784. */
  23785. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23786. /**
  23787. * An event triggered when active meshes evaluation is done
  23788. */
  23789. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23790. /**
  23791. * An event triggered when particles rendering is about to start
  23792. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23793. */
  23794. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23795. /**
  23796. * An event triggered when particles rendering is done
  23797. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23798. */
  23799. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when sprites rendering is about to start
  23802. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23803. */
  23804. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23805. /**
  23806. * An event triggered when sprites rendering is done
  23807. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23808. */
  23809. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23810. /**
  23811. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23812. */
  23813. this.onDataLoadedObservable = new BABYLON.Observable();
  23814. /**
  23815. * An event triggered when a camera is created
  23816. */
  23817. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23818. /**
  23819. * An event triggered when a camera is removed
  23820. */
  23821. this.onCameraRemovedObservable = new BABYLON.Observable();
  23822. /**
  23823. * An event triggered when a light is created
  23824. */
  23825. this.onNewLightAddedObservable = new BABYLON.Observable();
  23826. /**
  23827. * An event triggered when a light is removed
  23828. */
  23829. this.onLightRemovedObservable = new BABYLON.Observable();
  23830. /**
  23831. * An event triggered when a geometry is created
  23832. */
  23833. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23834. /**
  23835. * An event triggered when a geometry is removed
  23836. */
  23837. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23838. /**
  23839. * An event triggered when a transform node is created
  23840. */
  23841. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23842. /**
  23843. * An event triggered when a transform node is removed
  23844. */
  23845. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23846. /**
  23847. * An event triggered when a mesh is created
  23848. */
  23849. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23850. /**
  23851. * An event triggered when a mesh is removed
  23852. */
  23853. this.onMeshRemovedObservable = new BABYLON.Observable();
  23854. /**
  23855. * An event triggered when render targets are about to be rendered
  23856. * Can happen multiple times per frame.
  23857. */
  23858. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23859. /**
  23860. * An event triggered when render targets were rendered.
  23861. * Can happen multiple times per frame.
  23862. */
  23863. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23864. /**
  23865. * An event triggered before calculating deterministic simulation step
  23866. */
  23867. this.onBeforeStepObservable = new BABYLON.Observable();
  23868. /**
  23869. * An event triggered after calculating deterministic simulation step
  23870. */
  23871. this.onAfterStepObservable = new BABYLON.Observable();
  23872. /**
  23873. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23874. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23875. * 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)
  23876. */
  23877. this.onRenderingGroupObservable = new BABYLON.Observable();
  23878. // Animations
  23879. /**
  23880. * Gets a list of Animations associated with the scene
  23881. */
  23882. this.animations = [];
  23883. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23884. /**
  23885. * 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).
  23886. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23887. */
  23888. this.onPrePointerObservable = new BABYLON.Observable();
  23889. /**
  23890. * Observable event triggered each time an input event is received from the rendering canvas
  23891. */
  23892. this.onPointerObservable = new BABYLON.Observable();
  23893. this._meshPickProceed = false;
  23894. this._currentPickResult = null;
  23895. this._previousPickResult = null;
  23896. this._totalPointersPressed = 0;
  23897. this._doubleClickOccured = false;
  23898. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23899. this.cameraToUseForPointers = null;
  23900. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23901. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23902. this._startingPointerTime = 0;
  23903. this._previousStartingPointerTime = 0;
  23904. this._pointerCaptures = {};
  23905. // Deterministic lockstep
  23906. this._timeAccumulator = 0;
  23907. this._currentStepId = 0;
  23908. this._currentInternalStep = 0;
  23909. // Keyboard
  23910. /**
  23911. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23912. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23913. */
  23914. this.onPreKeyboardObservable = new BABYLON.Observable();
  23915. /**
  23916. * Observable event triggered each time an keyboard event is received from the hosting window
  23917. */
  23918. this.onKeyboardObservable = new BABYLON.Observable();
  23919. // Coordinates system
  23920. this._useRightHandedSystem = false;
  23921. // Fog
  23922. this._fogEnabled = true;
  23923. this._fogMode = Scene.FOGMODE_NONE;
  23924. /**
  23925. * Gets or sets the fog color to use
  23926. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23927. */
  23928. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23929. /**
  23930. * Gets or sets the fog density to use
  23931. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23932. */
  23933. this.fogDensity = 0.1;
  23934. /**
  23935. * Gets or sets the fog start distance to use
  23936. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23937. */
  23938. this.fogStart = 0;
  23939. /**
  23940. * Gets or sets the fog end distance to use
  23941. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23942. */
  23943. this.fogEnd = 1000.0;
  23944. // Lights
  23945. this._shadowsEnabled = true;
  23946. this._lightsEnabled = true;
  23947. /**
  23948. * All of the lights added to this scene
  23949. * @see http://doc.babylonjs.com/babylon101/lights
  23950. */
  23951. this.lights = new Array();
  23952. // Cameras
  23953. /** All of the cameras added to this scene.
  23954. * @see http://doc.babylonjs.com/babylon101/cameras
  23955. */
  23956. this.cameras = new Array();
  23957. /** All of the active cameras added to this scene. */
  23958. this.activeCameras = new Array();
  23959. // Meshes
  23960. /**
  23961. * All of the tranform nodes added to this scene
  23962. * @see http://doc.babylonjs.com/how_to/transformnode
  23963. */
  23964. this.transformNodes = new Array();
  23965. /**
  23966. * All of the (abstract) meshes added to this scene
  23967. */
  23968. this.meshes = new Array();
  23969. /**
  23970. * All of the animation groups added to this scene
  23971. * @see http://doc.babylonjs.com/how_to/group
  23972. */
  23973. this.animationGroups = new Array();
  23974. // Geometries
  23975. this._geometries = new Array();
  23976. /**
  23977. * All of the materials added to this scene
  23978. * @see http://doc.babylonjs.com/babylon101/materials
  23979. */
  23980. this.materials = new Array();
  23981. /**
  23982. * All of the multi-materials added to this scene
  23983. * @see http://doc.babylonjs.com/how_to/multi_materials
  23984. */
  23985. this.multiMaterials = new Array();
  23986. // Textures
  23987. this._texturesEnabled = true;
  23988. /**
  23989. * All of the textures added to this scene
  23990. */
  23991. this.textures = new Array();
  23992. // Particles
  23993. /**
  23994. * Gets or sets a boolean indicating if particles are enabled on this scene
  23995. */
  23996. this.particlesEnabled = true;
  23997. /**
  23998. * All of the particle systems added to this scene
  23999. * @see http://doc.babylonjs.com/babylon101/particles
  24000. */
  24001. this.particleSystems = new Array();
  24002. // Sprites
  24003. /**
  24004. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24005. */
  24006. this.spritesEnabled = true;
  24007. /**
  24008. * All of the sprite managers added to this scene
  24009. * @see http://doc.babylonjs.com/babylon101/sprites
  24010. */
  24011. this.spriteManagers = new Array();
  24012. /**
  24013. * The list of layers (background and foreground) of the scene
  24014. */
  24015. this.layers = new Array();
  24016. /**
  24017. * The list of effect layers (highlights/glow) added to the scene
  24018. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24019. * @see http://doc.babylonjs.com/how_to/glow_layer
  24020. */
  24021. this.effectLayers = new Array();
  24022. // Skeletons
  24023. this._skeletonsEnabled = true;
  24024. /**
  24025. * The list of skeletons added to the scene
  24026. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24027. */
  24028. this.skeletons = new Array();
  24029. // Morph targets
  24030. /**
  24031. * The list of morph target managers added to the scene
  24032. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24033. */
  24034. this.morphTargetManagers = new Array();
  24035. // Lens flares
  24036. /**
  24037. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24038. */
  24039. this.lensFlaresEnabled = true;
  24040. /**
  24041. * The list of lens flare system added to the scene
  24042. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24043. */
  24044. this.lensFlareSystems = new Array();
  24045. // Collisions
  24046. /**
  24047. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24048. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24049. */
  24050. this.collisionsEnabled = true;
  24051. /**
  24052. * Defines the gravity applied to this scene (used only for collisions)
  24053. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24054. */
  24055. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24056. // Postprocesses
  24057. /**
  24058. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24059. */
  24060. this.postProcessesEnabled = true;
  24061. /**
  24062. * The list of postprocesses added to the scene
  24063. */
  24064. this.postProcesses = new Array();
  24065. // Customs render targets
  24066. /**
  24067. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24068. */
  24069. this.renderTargetsEnabled = true;
  24070. /**
  24071. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24072. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24073. */
  24074. this.dumpNextRenderTargets = false;
  24075. /**
  24076. * The list of user defined render targets added to the scene
  24077. */
  24078. this.customRenderTargets = new Array();
  24079. /**
  24080. * Gets the list of meshes imported to the scene through SceneLoader
  24081. */
  24082. this.importedMeshesFiles = new Array();
  24083. // Probes
  24084. /**
  24085. * Gets or sets a boolean indicating if probes are enabled on this scene
  24086. */
  24087. this.probesEnabled = true;
  24088. /**
  24089. * The list of reflection probes added to the scene
  24090. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24091. */
  24092. this.reflectionProbes = new Array();
  24093. /** @hidden */
  24094. this._actionManagers = new Array();
  24095. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24096. // Procedural textures
  24097. /**
  24098. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24099. */
  24100. this.proceduralTexturesEnabled = true;
  24101. /**
  24102. * The list of procedural textures added to the scene
  24103. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24104. */
  24105. this.proceduralTextures = new Array();
  24106. /**
  24107. * The list of sound tracks added to the scene
  24108. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24109. */
  24110. this.soundTracks = new Array();
  24111. this._audioEnabled = true;
  24112. this._headphone = false;
  24113. // Performance counters
  24114. this._totalVertices = new BABYLON.PerfCounter();
  24115. /** @hidden */
  24116. this._activeIndices = new BABYLON.PerfCounter();
  24117. /** @hidden */
  24118. this._activeParticles = new BABYLON.PerfCounter();
  24119. /** @hidden */
  24120. this._activeBones = new BABYLON.PerfCounter();
  24121. this._animationTime = 0;
  24122. /**
  24123. * Gets or sets a general scale for animation speed
  24124. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24125. */
  24126. this.animationTimeScale = 1;
  24127. this._renderId = 0;
  24128. this._executeWhenReadyTimeoutId = -1;
  24129. this._intermediateRendering = false;
  24130. this._viewUpdateFlag = -1;
  24131. this._projectionUpdateFlag = -1;
  24132. this._alternateViewUpdateFlag = -1;
  24133. this._alternateProjectionUpdateFlag = -1;
  24134. /** @hidden */
  24135. this._toBeDisposed = new BABYLON.SmartArray(256);
  24136. this._activeRequests = new Array();
  24137. this._pendingData = new Array();
  24138. this._isDisposed = false;
  24139. /**
  24140. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24141. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24142. */
  24143. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24144. this._activeMeshes = new BABYLON.SmartArray(256);
  24145. this._processedMaterials = new BABYLON.SmartArray(256);
  24146. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24147. /** @hidden */
  24148. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24149. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24150. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24151. /** @hidden */
  24152. this._activeAnimatables = new Array();
  24153. this._transformMatrix = BABYLON.Matrix.Zero();
  24154. this._useAlternateCameraConfiguration = false;
  24155. this._alternateRendering = false;
  24156. /**
  24157. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24158. * This is useful if there are more lights that the maximum simulteanous authorized
  24159. */
  24160. this.requireLightSorting = false;
  24161. this._depthRenderer = {};
  24162. this._activeMeshesFrozen = false;
  24163. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24164. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24165. this._engine.scenes.push(this);
  24166. this._uid = null;
  24167. this._renderingManager = new BABYLON.RenderingManager(this);
  24168. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24169. if (BABYLON.OutlineRenderer) {
  24170. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24171. }
  24172. if (BABYLON.Tools.IsWindowObjectExist()) {
  24173. this.attachControl();
  24174. }
  24175. //simplification queue
  24176. if (BABYLON.SimplificationQueue) {
  24177. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24178. }
  24179. //collision coordinator initialization. For now legacy per default.
  24180. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24181. // Uniform Buffer
  24182. this._createUbo();
  24183. // Default Image processing definition.
  24184. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24185. }
  24186. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24187. /** The fog is deactivated */
  24188. get: function () {
  24189. return Scene._FOGMODE_NONE;
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24195. /** The fog density is following an exponential function */
  24196. get: function () {
  24197. return Scene._FOGMODE_EXP;
  24198. },
  24199. enumerable: true,
  24200. configurable: true
  24201. });
  24202. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24203. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24204. get: function () {
  24205. return Scene._FOGMODE_EXP2;
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24211. /** The fog density is following a linear function. */
  24212. get: function () {
  24213. return Scene._FOGMODE_LINEAR;
  24214. },
  24215. enumerable: true,
  24216. configurable: true
  24217. });
  24218. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24219. /**
  24220. * Texture used in all pbr material as the reflection texture.
  24221. * As in the majority of the scene they are the same (exception for multi room and so on),
  24222. * this is easier to reference from here than from all the materials.
  24223. */
  24224. get: function () {
  24225. return this._environmentTexture;
  24226. },
  24227. /**
  24228. * Texture used in all pbr material as the reflection texture.
  24229. * As in the majority of the scene they are the same (exception for multi room and so on),
  24230. * this is easier to set here than in all the materials.
  24231. */
  24232. set: function (value) {
  24233. if (this._environmentTexture === value) {
  24234. return;
  24235. }
  24236. this._environmentTexture = value;
  24237. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24238. },
  24239. enumerable: true,
  24240. configurable: true
  24241. });
  24242. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24243. /**
  24244. * Default image processing configuration used either in the rendering
  24245. * Forward main pass or through the imageProcessingPostProcess if present.
  24246. * As in the majority of the scene they are the same (exception for multi camera),
  24247. * this is easier to reference from here than from all the materials and post process.
  24248. *
  24249. * No setter as we it is a shared configuration, you can set the values instead.
  24250. */
  24251. get: function () {
  24252. return this._imageProcessingConfiguration;
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24258. get: function () {
  24259. return this._forceWireframe;
  24260. },
  24261. /**
  24262. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24263. */
  24264. set: function (value) {
  24265. if (this._forceWireframe === value) {
  24266. return;
  24267. }
  24268. this._forceWireframe = value;
  24269. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24270. },
  24271. enumerable: true,
  24272. configurable: true
  24273. });
  24274. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24275. get: function () {
  24276. return this._forcePointsCloud;
  24277. },
  24278. /**
  24279. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24280. */
  24281. set: function (value) {
  24282. if (this._forcePointsCloud === value) {
  24283. return;
  24284. }
  24285. this._forcePointsCloud = value;
  24286. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24287. },
  24288. enumerable: true,
  24289. configurable: true
  24290. });
  24291. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24292. /**
  24293. * Gets or sets the animation properties override
  24294. */
  24295. get: function () {
  24296. return this._animationPropertiesOverride;
  24297. },
  24298. set: function (value) {
  24299. this._animationPropertiesOverride = value;
  24300. },
  24301. enumerable: true,
  24302. configurable: true
  24303. });
  24304. Object.defineProperty(Scene.prototype, "onDispose", {
  24305. /** Sets a function to be executed when this scene is disposed. */
  24306. set: function (callback) {
  24307. if (this._onDisposeObserver) {
  24308. this.onDisposeObservable.remove(this._onDisposeObserver);
  24309. }
  24310. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24311. },
  24312. enumerable: true,
  24313. configurable: true
  24314. });
  24315. Object.defineProperty(Scene.prototype, "beforeRender", {
  24316. /** Sets a function to be executed before rendering this scene */
  24317. set: function (callback) {
  24318. if (this._onBeforeRenderObserver) {
  24319. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24320. }
  24321. if (callback) {
  24322. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24323. }
  24324. },
  24325. enumerable: true,
  24326. configurable: true
  24327. });
  24328. Object.defineProperty(Scene.prototype, "afterRender", {
  24329. /** Sets a function to be executed after rendering this scene */
  24330. set: function (callback) {
  24331. if (this._onAfterRenderObserver) {
  24332. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24333. }
  24334. if (callback) {
  24335. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24336. }
  24337. },
  24338. enumerable: true,
  24339. configurable: true
  24340. });
  24341. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24342. /** Sets a function to be executed before rendering a camera*/
  24343. set: function (callback) {
  24344. if (this._onBeforeCameraRenderObserver) {
  24345. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24346. }
  24347. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24348. },
  24349. enumerable: true,
  24350. configurable: true
  24351. });
  24352. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24353. /** Sets a function to be executed after rendering a camera*/
  24354. set: function (callback) {
  24355. if (this._onAfterCameraRenderObserver) {
  24356. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24357. }
  24358. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24359. },
  24360. enumerable: true,
  24361. configurable: true
  24362. });
  24363. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24364. /**
  24365. * Gets the gamepad manager associated with the scene
  24366. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24367. */
  24368. get: function () {
  24369. if (!this._gamepadManager) {
  24370. this._gamepadManager = new BABYLON.GamepadManager(this);
  24371. }
  24372. return this._gamepadManager;
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24378. /**
  24379. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24380. */
  24381. get: function () {
  24382. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24388. get: function () {
  24389. return this._useRightHandedSystem;
  24390. },
  24391. /**
  24392. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24393. */
  24394. set: function (value) {
  24395. if (this._useRightHandedSystem === value) {
  24396. return;
  24397. }
  24398. this._useRightHandedSystem = value;
  24399. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. /**
  24405. * Sets the step Id used by deterministic lock step
  24406. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24407. * @param newStepId defines the step Id
  24408. */
  24409. Scene.prototype.setStepId = function (newStepId) {
  24410. this._currentStepId = newStepId;
  24411. };
  24412. ;
  24413. /**
  24414. * Gets the step Id used by deterministic lock step
  24415. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24416. * @returns the step Id
  24417. */
  24418. Scene.prototype.getStepId = function () {
  24419. return this._currentStepId;
  24420. };
  24421. ;
  24422. /**
  24423. * Gets the internal step used by deterministic lock step
  24424. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24425. * @returns the internal step
  24426. */
  24427. Scene.prototype.getInternalStep = function () {
  24428. return this._currentInternalStep;
  24429. };
  24430. ;
  24431. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24432. get: function () {
  24433. return this._fogEnabled;
  24434. },
  24435. /**
  24436. * Gets or sets a boolean indicating if fog is enabled on this scene
  24437. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24438. */
  24439. set: function (value) {
  24440. if (this._fogEnabled === value) {
  24441. return;
  24442. }
  24443. this._fogEnabled = value;
  24444. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "fogMode", {
  24450. get: function () {
  24451. return this._fogMode;
  24452. },
  24453. /**
  24454. * Gets or sets the fog mode to use
  24455. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24456. */
  24457. set: function (value) {
  24458. if (this._fogMode === value) {
  24459. return;
  24460. }
  24461. this._fogMode = value;
  24462. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24468. get: function () {
  24469. return this._shadowsEnabled;
  24470. },
  24471. /**
  24472. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24473. */
  24474. set: function (value) {
  24475. if (this._shadowsEnabled === value) {
  24476. return;
  24477. }
  24478. this._shadowsEnabled = value;
  24479. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24485. get: function () {
  24486. return this._lightsEnabled;
  24487. },
  24488. /**
  24489. * Gets or sets a boolean indicating if lights are enabled on this scene
  24490. */
  24491. set: function (value) {
  24492. if (this._lightsEnabled === value) {
  24493. return;
  24494. }
  24495. this._lightsEnabled = value;
  24496. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24497. },
  24498. enumerable: true,
  24499. configurable: true
  24500. });
  24501. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24502. /** The default material used on meshes when no material is affected */
  24503. get: function () {
  24504. if (!this._defaultMaterial) {
  24505. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24506. }
  24507. return this._defaultMaterial;
  24508. },
  24509. /** The default material used on meshes when no material is affected */
  24510. set: function (value) {
  24511. this._defaultMaterial = value;
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24517. get: function () {
  24518. return this._texturesEnabled;
  24519. },
  24520. /**
  24521. * Gets or sets a boolean indicating if textures are enabled on this scene
  24522. */
  24523. set: function (value) {
  24524. if (this._texturesEnabled === value) {
  24525. return;
  24526. }
  24527. this._texturesEnabled = value;
  24528. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24534. get: function () {
  24535. return this._skeletonsEnabled;
  24536. },
  24537. /**
  24538. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24539. */
  24540. set: function (value) {
  24541. if (this._skeletonsEnabled === value) {
  24542. return;
  24543. }
  24544. this._skeletonsEnabled = value;
  24545. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24546. },
  24547. enumerable: true,
  24548. configurable: true
  24549. });
  24550. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24551. /**
  24552. * Gets the postprocess render pipeline manager
  24553. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24554. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24555. */
  24556. get: function () {
  24557. if (!this._postProcessRenderPipelineManager) {
  24558. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24559. }
  24560. return this._postProcessRenderPipelineManager;
  24561. },
  24562. enumerable: true,
  24563. configurable: true
  24564. });
  24565. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24566. /**
  24567. * Gets the main soundtrack associated with the scene
  24568. */
  24569. get: function () {
  24570. if (!this._mainSoundTrack) {
  24571. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24572. }
  24573. return this._mainSoundTrack;
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24579. /** @hidden */
  24580. get: function () {
  24581. return this._alternateRendering;
  24582. },
  24583. enumerable: true,
  24584. configurable: true
  24585. });
  24586. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24587. /**
  24588. * Gets the list of frustum planes (built from the active camera)
  24589. */
  24590. get: function () {
  24591. return this._frustumPlanes;
  24592. },
  24593. enumerable: true,
  24594. configurable: true
  24595. });
  24596. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24597. /**
  24598. * Gets the current geometry buffer associated to the scene.
  24599. */
  24600. get: function () {
  24601. return this._geometryBufferRenderer;
  24602. },
  24603. /**
  24604. * Sets the current geometry buffer for the scene.
  24605. */
  24606. set: function (geometryBufferRenderer) {
  24607. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24608. this._geometryBufferRenderer = geometryBufferRenderer;
  24609. }
  24610. },
  24611. enumerable: true,
  24612. configurable: true
  24613. });
  24614. Object.defineProperty(Scene.prototype, "debugLayer", {
  24615. /**
  24616. * Gets the debug layer associated with the scene
  24617. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24618. */
  24619. get: function () {
  24620. if (!this._debugLayer) {
  24621. this._debugLayer = new BABYLON.DebugLayer(this);
  24622. }
  24623. return this._debugLayer;
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24629. /**
  24630. * Gets a boolean indicating if collisions are processed on a web worker
  24631. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24632. */
  24633. get: function () {
  24634. return this._workerCollisions;
  24635. },
  24636. set: function (enabled) {
  24637. if (!BABYLON.CollisionCoordinatorLegacy) {
  24638. return;
  24639. }
  24640. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24641. this._workerCollisions = enabled;
  24642. if (this.collisionCoordinator) {
  24643. this.collisionCoordinator.destroy();
  24644. }
  24645. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24646. this.collisionCoordinator.init(this);
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24652. /**
  24653. * Gets the octree used to boost mesh selection (picking)
  24654. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24655. */
  24656. get: function () {
  24657. return this._selectionOctree;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24663. /**
  24664. * Gets the mesh that is currently under the pointer
  24665. */
  24666. get: function () {
  24667. return this._pointerOverMesh;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Object.defineProperty(Scene.prototype, "pointerX", {
  24673. /**
  24674. * Gets the current on-screen X position of the pointer
  24675. */
  24676. get: function () {
  24677. return this._pointerX;
  24678. },
  24679. enumerable: true,
  24680. configurable: true
  24681. });
  24682. Object.defineProperty(Scene.prototype, "pointerY", {
  24683. /**
  24684. * Gets the current on-screen Y position of the pointer
  24685. */
  24686. get: function () {
  24687. return this._pointerY;
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. /**
  24693. * Gets the cached material (ie. the latest rendered one)
  24694. * @returns the cached material
  24695. */
  24696. Scene.prototype.getCachedMaterial = function () {
  24697. return this._cachedMaterial;
  24698. };
  24699. /**
  24700. * Gets the cached effect (ie. the latest rendered one)
  24701. * @returns the cached effect
  24702. */
  24703. Scene.prototype.getCachedEffect = function () {
  24704. return this._cachedEffect;
  24705. };
  24706. /**
  24707. * Gets the cached visibility state (ie. the latest rendered one)
  24708. * @returns the cached visibility state
  24709. */
  24710. Scene.prototype.getCachedVisibility = function () {
  24711. return this._cachedVisibility;
  24712. };
  24713. /**
  24714. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24715. * @param material defines the current material
  24716. * @param effect defines the current effect
  24717. * @param visibility defines the current visibility state
  24718. * @returns true if one parameter is not cached
  24719. */
  24720. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24721. if (visibility === void 0) { visibility = 1; }
  24722. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24723. };
  24724. /**
  24725. * Gets the bounding box renderer associated with the scene
  24726. * @returns a BoundingBoxRenderer
  24727. */
  24728. Scene.prototype.getBoundingBoxRenderer = function () {
  24729. if (!this._boundingBoxRenderer) {
  24730. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24731. }
  24732. return this._boundingBoxRenderer;
  24733. };
  24734. /**
  24735. * Gets the outline renderer associated with the scene
  24736. * @returns a OutlineRenderer
  24737. */
  24738. Scene.prototype.getOutlineRenderer = function () {
  24739. return this._outlineRenderer;
  24740. };
  24741. /**
  24742. * Gets the engine associated with the scene
  24743. * @returns an Engine
  24744. */
  24745. Scene.prototype.getEngine = function () {
  24746. return this._engine;
  24747. };
  24748. /**
  24749. * Gets the total number of vertices rendered per frame
  24750. * @returns the total number of vertices rendered per frame
  24751. */
  24752. Scene.prototype.getTotalVertices = function () {
  24753. return this._totalVertices.current;
  24754. };
  24755. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24756. /**
  24757. * Gets the performance counter for total vertices
  24758. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24759. */
  24760. get: function () {
  24761. return this._totalVertices;
  24762. },
  24763. enumerable: true,
  24764. configurable: true
  24765. });
  24766. /**
  24767. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24768. * @returns the total number of active indices rendered per frame
  24769. */
  24770. Scene.prototype.getActiveIndices = function () {
  24771. return this._activeIndices.current;
  24772. };
  24773. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24774. /**
  24775. * Gets the performance counter for active indices
  24776. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24777. */
  24778. get: function () {
  24779. return this._activeIndices;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. /**
  24785. * Gets the total number of active particles rendered per frame
  24786. * @returns the total number of active particles rendered per frame
  24787. */
  24788. Scene.prototype.getActiveParticles = function () {
  24789. return this._activeParticles.current;
  24790. };
  24791. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24792. /**
  24793. * Gets the performance counter for active particles
  24794. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24795. */
  24796. get: function () {
  24797. return this._activeParticles;
  24798. },
  24799. enumerable: true,
  24800. configurable: true
  24801. });
  24802. /**
  24803. * Gets the total number of active bones rendered per frame
  24804. * @returns the total number of active bones rendered per frame
  24805. */
  24806. Scene.prototype.getActiveBones = function () {
  24807. return this._activeBones.current;
  24808. };
  24809. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24810. /**
  24811. * Gets the performance counter for active bones
  24812. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24813. */
  24814. get: function () {
  24815. return this._activeBones;
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. /** @hidden */
  24821. Scene.prototype.getInterFramePerfCounter = function () {
  24822. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24823. return 0;
  24824. };
  24825. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24826. /** @hidden */
  24827. get: function () {
  24828. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24829. return null;
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. /** @hidden */
  24835. Scene.prototype.getLastFrameDuration = function () {
  24836. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24837. return 0;
  24838. };
  24839. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24840. /** @hidden */
  24841. get: function () {
  24842. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24843. return null;
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. /** @hidden */
  24849. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24850. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24851. return 0;
  24852. };
  24853. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24854. /** @hidden */
  24855. get: function () {
  24856. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24857. return null;
  24858. },
  24859. enumerable: true,
  24860. configurable: true
  24861. });
  24862. /**
  24863. * Gets the array of active meshes
  24864. * @returns an array of AbstractMesh
  24865. */
  24866. Scene.prototype.getActiveMeshes = function () {
  24867. return this._activeMeshes;
  24868. };
  24869. /** @hidden */
  24870. Scene.prototype.getRenderTargetsDuration = function () {
  24871. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24872. return 0;
  24873. };
  24874. /** @hidden */
  24875. Scene.prototype.getRenderDuration = function () {
  24876. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24877. return 0;
  24878. };
  24879. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24880. /** @hidden */
  24881. get: function () {
  24882. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24883. return null;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. /** @hidden */
  24889. Scene.prototype.getParticlesDuration = function () {
  24890. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24891. return 0;
  24892. };
  24893. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24894. /** @hidden */
  24895. get: function () {
  24896. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24897. return null;
  24898. },
  24899. enumerable: true,
  24900. configurable: true
  24901. });
  24902. /** @hidden */
  24903. Scene.prototype.getSpritesDuration = function () {
  24904. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24905. return 0;
  24906. };
  24907. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24908. /** @hidden */
  24909. get: function () {
  24910. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24911. return null;
  24912. },
  24913. enumerable: true,
  24914. configurable: true
  24915. });
  24916. /**
  24917. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24918. * @returns a number
  24919. */
  24920. Scene.prototype.getAnimationRatio = function () {
  24921. return this._animationRatio;
  24922. };
  24923. /**
  24924. * Gets an unique Id for the current frame
  24925. * @returns a number
  24926. */
  24927. Scene.prototype.getRenderId = function () {
  24928. return this._renderId;
  24929. };
  24930. /** Call this function if you want to manually increment the render Id*/
  24931. Scene.prototype.incrementRenderId = function () {
  24932. this._renderId++;
  24933. };
  24934. Scene.prototype._updatePointerPosition = function (evt) {
  24935. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24936. if (!canvasRect) {
  24937. return;
  24938. }
  24939. this._pointerX = evt.clientX - canvasRect.left;
  24940. this._pointerY = evt.clientY - canvasRect.top;
  24941. this._unTranslatedPointerX = this._pointerX;
  24942. this._unTranslatedPointerY = this._pointerY;
  24943. };
  24944. Scene.prototype._createUbo = function () {
  24945. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24946. this._sceneUbo.addUniform("viewProjection", 16);
  24947. this._sceneUbo.addUniform("view", 16);
  24948. };
  24949. Scene.prototype._createAlternateUbo = function () {
  24950. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24951. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24952. this._alternateSceneUbo.addUniform("view", 16);
  24953. };
  24954. // Pointers handling
  24955. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24956. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24957. if (result) {
  24958. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24959. }
  24960. return result;
  24961. };
  24962. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24963. if (pointerInfo.pickInfo) {
  24964. if (!pointerInfo.pickInfo.ray) {
  24965. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24966. }
  24967. }
  24968. };
  24969. /**
  24970. * Use this method to simulate a pointer move on a mesh
  24971. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24972. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24973. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24974. * @returns the current scene
  24975. */
  24976. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24977. var evt = new PointerEvent("pointermove", pointerEventInit);
  24978. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24979. return this;
  24980. }
  24981. return this._processPointerMove(pickResult, evt);
  24982. };
  24983. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24984. var canvas = this._engine.getRenderingCanvas();
  24985. if (!canvas) {
  24986. return this;
  24987. }
  24988. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24989. this.setPointerOverSprite(null);
  24990. this.setPointerOverMesh(pickResult.pickedMesh);
  24991. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24992. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24993. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24994. }
  24995. else {
  24996. canvas.style.cursor = this.hoverCursor;
  24997. }
  24998. }
  24999. else {
  25000. canvas.style.cursor = this.defaultCursor;
  25001. }
  25002. }
  25003. else {
  25004. this.setPointerOverMesh(null);
  25005. // Sprites
  25006. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25007. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25008. this.setPointerOverSprite(pickResult.pickedSprite);
  25009. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25010. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25011. }
  25012. else {
  25013. canvas.style.cursor = this.hoverCursor;
  25014. }
  25015. }
  25016. else {
  25017. this.setPointerOverSprite(null);
  25018. // Restore pointer
  25019. canvas.style.cursor = this.defaultCursor;
  25020. }
  25021. }
  25022. if (pickResult) {
  25023. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25024. if (this.onPointerMove) {
  25025. this.onPointerMove(evt, pickResult, type);
  25026. }
  25027. if (this.onPointerObservable.hasObservers()) {
  25028. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25029. this._setRayOnPointerInfo(pi);
  25030. this.onPointerObservable.notifyObservers(pi, type);
  25031. }
  25032. }
  25033. return this;
  25034. };
  25035. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25036. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25037. if (pickResult) {
  25038. pi.ray = pickResult.ray;
  25039. }
  25040. this.onPrePointerObservable.notifyObservers(pi, type);
  25041. if (pi.skipOnPointerObservable) {
  25042. return true;
  25043. }
  25044. else {
  25045. return false;
  25046. }
  25047. };
  25048. /**
  25049. * Use this method to simulate a pointer down on a mesh
  25050. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25051. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25052. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25053. * @returns the current scene
  25054. */
  25055. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25056. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25057. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25058. return this;
  25059. }
  25060. return this._processPointerDown(pickResult, evt);
  25061. };
  25062. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25063. var _this = this;
  25064. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25065. this._pickedDownMesh = pickResult.pickedMesh;
  25066. var actionManager = pickResult.pickedMesh.actionManager;
  25067. if (actionManager) {
  25068. if (actionManager.hasPickTriggers) {
  25069. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25070. switch (evt.button) {
  25071. case 0:
  25072. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25073. break;
  25074. case 1:
  25075. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25076. break;
  25077. case 2:
  25078. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25079. break;
  25080. }
  25081. }
  25082. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25083. window.setTimeout(function () {
  25084. 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);
  25085. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25086. if (_this._totalPointersPressed !== 0 &&
  25087. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25088. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25089. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25090. _this._startingPointerTime = 0;
  25091. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25092. }
  25093. }
  25094. }, Scene.LongPressDelay);
  25095. }
  25096. }
  25097. }
  25098. if (pickResult) {
  25099. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25100. if (this.onPointerDown) {
  25101. this.onPointerDown(evt, pickResult, type);
  25102. }
  25103. if (this.onPointerObservable.hasObservers()) {
  25104. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25105. this._setRayOnPointerInfo(pi);
  25106. this.onPointerObservable.notifyObservers(pi, type);
  25107. }
  25108. }
  25109. return this;
  25110. };
  25111. /**
  25112. * Use this method to simulate a pointer up on a mesh
  25113. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25114. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25115. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25116. * @returns the current scene
  25117. */
  25118. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25119. var evt = new PointerEvent("pointerup", pointerEventInit);
  25120. var clickInfo = new ClickInfo();
  25121. clickInfo.singleClick = true;
  25122. clickInfo.ignore = true;
  25123. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25124. return this;
  25125. }
  25126. return this._processPointerUp(pickResult, evt, clickInfo);
  25127. };
  25128. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25129. if (pickResult && pickResult && pickResult.pickedMesh) {
  25130. this._pickedUpMesh = pickResult.pickedMesh;
  25131. if (this._pickedDownMesh === this._pickedUpMesh) {
  25132. if (this.onPointerPick) {
  25133. this.onPointerPick(evt, pickResult);
  25134. }
  25135. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25136. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25137. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25138. this._setRayOnPointerInfo(pi);
  25139. this.onPointerObservable.notifyObservers(pi, type_1);
  25140. }
  25141. }
  25142. if (pickResult.pickedMesh.actionManager) {
  25143. if (clickInfo.ignore) {
  25144. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25145. }
  25146. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25147. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25148. }
  25149. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25150. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25151. }
  25152. }
  25153. }
  25154. if (this._pickedDownMesh &&
  25155. this._pickedDownMesh.actionManager &&
  25156. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25157. this._pickedDownMesh !== this._pickedUpMesh) {
  25158. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25159. }
  25160. var type = BABYLON.PointerEventTypes.POINTERUP;
  25161. if (this.onPointerObservable.hasObservers()) {
  25162. if (!clickInfo.ignore) {
  25163. if (!clickInfo.hasSwiped) {
  25164. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25165. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25166. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25167. this._setRayOnPointerInfo(pi);
  25168. this.onPointerObservable.notifyObservers(pi, type_2);
  25169. }
  25170. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25171. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25172. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25173. this._setRayOnPointerInfo(pi);
  25174. this.onPointerObservable.notifyObservers(pi, type_3);
  25175. }
  25176. }
  25177. }
  25178. else {
  25179. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25180. this._setRayOnPointerInfo(pi);
  25181. this.onPointerObservable.notifyObservers(pi, type);
  25182. }
  25183. }
  25184. if (this.onPointerUp) {
  25185. this.onPointerUp(evt, pickResult, type);
  25186. }
  25187. return this;
  25188. };
  25189. /**
  25190. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25191. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25192. * @returns true if the pointer was captured
  25193. */
  25194. Scene.prototype.isPointerCaptured = function (pointerId) {
  25195. if (pointerId === void 0) { pointerId = 0; }
  25196. return this._pointerCaptures[pointerId];
  25197. };
  25198. /**
  25199. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25200. * @param attachUp defines if you want to attach events to pointerup
  25201. * @param attachDown defines if you want to attach events to pointerdown
  25202. * @param attachMove defines if you want to attach events to pointermove
  25203. */
  25204. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25205. var _this = this;
  25206. if (attachUp === void 0) { attachUp = true; }
  25207. if (attachDown === void 0) { attachDown = true; }
  25208. if (attachMove === void 0) { attachMove = true; }
  25209. this._initActionManager = function (act, clickInfo) {
  25210. if (!_this._meshPickProceed) {
  25211. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25212. _this._currentPickResult = pickResult;
  25213. if (pickResult) {
  25214. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25215. }
  25216. _this._meshPickProceed = true;
  25217. }
  25218. return act;
  25219. };
  25220. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25221. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25222. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25223. btn !== _this._previousButtonPressed) {
  25224. _this._doubleClickOccured = false;
  25225. clickInfo.singleClick = true;
  25226. clickInfo.ignore = false;
  25227. cb(clickInfo, _this._currentPickResult);
  25228. }
  25229. };
  25230. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25231. var clickInfo = new ClickInfo();
  25232. _this._currentPickResult = null;
  25233. var act = null;
  25234. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25235. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25236. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25237. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25238. act = _this._initActionManager(act, clickInfo);
  25239. if (act)
  25240. checkPicking = act.hasPickTriggers;
  25241. }
  25242. if (checkPicking) {
  25243. var btn = evt.button;
  25244. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25245. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25246. if (!clickInfo.hasSwiped) {
  25247. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25248. if (!checkSingleClickImmediately) {
  25249. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25250. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25251. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25252. act = _this._initActionManager(act, clickInfo);
  25253. if (act)
  25254. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25255. }
  25256. }
  25257. if (checkSingleClickImmediately) {
  25258. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25259. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25260. btn !== _this._previousButtonPressed) {
  25261. clickInfo.singleClick = true;
  25262. cb(clickInfo, _this._currentPickResult);
  25263. }
  25264. }
  25265. // at least one double click is required to be check and exclusive double click is enabled
  25266. else {
  25267. // wait that no double click has been raised during the double click delay
  25268. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25269. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25270. }
  25271. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25272. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25273. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25274. act = _this._initActionManager(act, clickInfo);
  25275. if (act)
  25276. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25277. }
  25278. if (checkDoubleClick) {
  25279. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25280. if (btn === _this._previousButtonPressed &&
  25281. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25282. !_this._doubleClickOccured) {
  25283. // pointer has not moved for 2 clicks, it's a double click
  25284. if (!clickInfo.hasSwiped &&
  25285. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25286. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25287. _this._previousStartingPointerTime = 0;
  25288. _this._doubleClickOccured = true;
  25289. clickInfo.doubleClick = true;
  25290. clickInfo.ignore = false;
  25291. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25292. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25293. }
  25294. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25295. cb(clickInfo, _this._currentPickResult);
  25296. }
  25297. // if the two successive clicks are too far, it's just two simple clicks
  25298. else {
  25299. _this._doubleClickOccured = false;
  25300. _this._previousStartingPointerTime = _this._startingPointerTime;
  25301. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25302. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25303. _this._previousButtonPressed = btn;
  25304. if (Scene.ExclusiveDoubleClickMode) {
  25305. if (_this._previousDelayedSimpleClickTimeout) {
  25306. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25307. }
  25308. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25309. cb(clickInfo, _this._previousPickResult);
  25310. }
  25311. else {
  25312. cb(clickInfo, _this._currentPickResult);
  25313. }
  25314. }
  25315. }
  25316. // just the first click of the double has been raised
  25317. else {
  25318. _this._doubleClickOccured = false;
  25319. _this._previousStartingPointerTime = _this._startingPointerTime;
  25320. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25321. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25322. _this._previousButtonPressed = btn;
  25323. }
  25324. }
  25325. }
  25326. }
  25327. clickInfo.ignore = true;
  25328. cb(clickInfo, _this._currentPickResult);
  25329. };
  25330. this._spritePredicate = function (sprite) {
  25331. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25332. };
  25333. this._onPointerMove = function (evt) {
  25334. _this._updatePointerPosition(evt);
  25335. // PreObservable support
  25336. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25337. return;
  25338. }
  25339. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25340. return;
  25341. }
  25342. if (!_this.pointerMovePredicate) {
  25343. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25344. }
  25345. // Meshes
  25346. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25347. _this._processPointerMove(pickResult, evt);
  25348. };
  25349. this._onPointerDown = function (evt) {
  25350. _this._totalPointersPressed++;
  25351. _this._pickedDownMesh = null;
  25352. _this._meshPickProceed = false;
  25353. _this._updatePointerPosition(evt);
  25354. if (_this.preventDefaultOnPointerDown && canvas) {
  25355. evt.preventDefault();
  25356. canvas.focus();
  25357. }
  25358. // PreObservable support
  25359. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25360. return;
  25361. }
  25362. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25363. return;
  25364. }
  25365. _this._pointerCaptures[evt.pointerId] = true;
  25366. _this._startingPointerPosition.x = _this._pointerX;
  25367. _this._startingPointerPosition.y = _this._pointerY;
  25368. _this._startingPointerTime = Date.now();
  25369. if (!_this.pointerDownPredicate) {
  25370. _this.pointerDownPredicate = function (mesh) {
  25371. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25372. };
  25373. }
  25374. // Meshes
  25375. _this._pickedDownMesh = null;
  25376. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25377. _this._processPointerDown(pickResult, evt);
  25378. // Sprites
  25379. _this._pickedDownSprite = null;
  25380. if (_this.spriteManagers.length > 0) {
  25381. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25382. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25383. if (pickResult.pickedSprite.actionManager) {
  25384. _this._pickedDownSprite = pickResult.pickedSprite;
  25385. switch (evt.button) {
  25386. case 0:
  25387. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25388. break;
  25389. case 1:
  25390. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25391. break;
  25392. case 2:
  25393. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25394. break;
  25395. }
  25396. if (pickResult.pickedSprite.actionManager) {
  25397. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25398. }
  25399. }
  25400. }
  25401. }
  25402. };
  25403. this._onPointerUp = function (evt) {
  25404. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25405. return; // So we need to test it the pointer down was pressed before.
  25406. }
  25407. _this._totalPointersPressed--;
  25408. _this._pickedUpMesh = null;
  25409. _this._meshPickProceed = false;
  25410. _this._updatePointerPosition(evt);
  25411. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25412. // PreObservable support
  25413. if (_this.onPrePointerObservable.hasObservers()) {
  25414. if (!clickInfo.ignore) {
  25415. if (!clickInfo.hasSwiped) {
  25416. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25417. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25418. return;
  25419. }
  25420. }
  25421. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25422. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25423. return;
  25424. }
  25425. }
  25426. }
  25427. }
  25428. else {
  25429. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25430. return;
  25431. }
  25432. }
  25433. }
  25434. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25435. return;
  25436. }
  25437. _this._pointerCaptures[evt.pointerId] = false;
  25438. if (!_this.pointerUpPredicate) {
  25439. _this.pointerUpPredicate = function (mesh) {
  25440. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25441. };
  25442. }
  25443. // Meshes
  25444. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25445. _this._initActionManager(null, clickInfo);
  25446. }
  25447. if (!pickResult) {
  25448. pickResult = _this._currentPickResult;
  25449. }
  25450. _this._processPointerUp(pickResult, evt, clickInfo);
  25451. // Sprites
  25452. if (!clickInfo.ignore) {
  25453. if (_this.spriteManagers.length > 0) {
  25454. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25455. if (spritePickResult) {
  25456. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25457. if (spritePickResult.pickedSprite.actionManager) {
  25458. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25459. if (spritePickResult.pickedSprite.actionManager) {
  25460. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25461. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25462. }
  25463. }
  25464. }
  25465. }
  25466. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25467. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25468. }
  25469. }
  25470. }
  25471. }
  25472. _this._previousPickResult = _this._currentPickResult;
  25473. });
  25474. };
  25475. this._onKeyDown = function (evt) {
  25476. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25477. if (_this.onPreKeyboardObservable.hasObservers()) {
  25478. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25479. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25480. if (pi.skipOnPointerObservable) {
  25481. return;
  25482. }
  25483. }
  25484. if (_this.onKeyboardObservable.hasObservers()) {
  25485. var pi = new BABYLON.KeyboardInfo(type, evt);
  25486. _this.onKeyboardObservable.notifyObservers(pi, type);
  25487. }
  25488. if (_this.actionManager) {
  25489. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25490. }
  25491. };
  25492. this._onKeyUp = function (evt) {
  25493. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25494. if (_this.onPreKeyboardObservable.hasObservers()) {
  25495. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25496. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25497. if (pi.skipOnPointerObservable) {
  25498. return;
  25499. }
  25500. }
  25501. if (_this.onKeyboardObservable.hasObservers()) {
  25502. var pi = new BABYLON.KeyboardInfo(type, evt);
  25503. _this.onKeyboardObservable.notifyObservers(pi, type);
  25504. }
  25505. if (_this.actionManager) {
  25506. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25507. }
  25508. };
  25509. var engine = this.getEngine();
  25510. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25511. if (!canvas) {
  25512. return;
  25513. }
  25514. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25515. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25516. });
  25517. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25518. if (!canvas) {
  25519. return;
  25520. }
  25521. canvas.removeEventListener("keydown", _this._onKeyDown);
  25522. canvas.removeEventListener("keyup", _this._onKeyUp);
  25523. });
  25524. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25525. var canvas = this._engine.getRenderingCanvas();
  25526. if (!canvas) {
  25527. return;
  25528. }
  25529. if (attachMove) {
  25530. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25531. // Wheel
  25532. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25533. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25534. }
  25535. if (attachDown) {
  25536. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25537. }
  25538. if (attachUp) {
  25539. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25540. }
  25541. canvas.tabIndex = 1;
  25542. };
  25543. /** Detaches all event handlers*/
  25544. Scene.prototype.detachControl = function () {
  25545. var engine = this.getEngine();
  25546. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25547. var canvas = engine.getRenderingCanvas();
  25548. if (!canvas) {
  25549. return;
  25550. }
  25551. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25552. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25553. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25554. if (this._onCanvasBlurObserver) {
  25555. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25556. }
  25557. if (this._onCanvasFocusObserver) {
  25558. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25559. }
  25560. // Wheel
  25561. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25562. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25563. // Keyboard
  25564. canvas.removeEventListener("keydown", this._onKeyDown);
  25565. canvas.removeEventListener("keyup", this._onKeyUp);
  25566. // Observables
  25567. this.onKeyboardObservable.clear();
  25568. this.onPreKeyboardObservable.clear();
  25569. this.onPointerObservable.clear();
  25570. this.onPrePointerObservable.clear();
  25571. };
  25572. /**
  25573. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25574. * Delay loaded resources are not taking in account
  25575. * @return true if all required resources are ready
  25576. */
  25577. Scene.prototype.isReady = function () {
  25578. if (this._isDisposed) {
  25579. return false;
  25580. }
  25581. if (this._pendingData.length > 0) {
  25582. return false;
  25583. }
  25584. var index;
  25585. var engine = this.getEngine();
  25586. // Geometries
  25587. for (index = 0; index < this._geometries.length; index++) {
  25588. var geometry = this._geometries[index];
  25589. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25590. return false;
  25591. }
  25592. }
  25593. // Meshes
  25594. for (index = 0; index < this.meshes.length; index++) {
  25595. var mesh = this.meshes[index];
  25596. if (!mesh.isEnabled()) {
  25597. continue;
  25598. }
  25599. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25600. continue;
  25601. }
  25602. if (!mesh.isReady(true)) {
  25603. return false;
  25604. }
  25605. // Effect layers
  25606. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25607. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25608. var layer = _a[_i];
  25609. if (!layer.hasMesh(mesh)) {
  25610. continue;
  25611. }
  25612. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25613. var subMesh = _c[_b];
  25614. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25615. return false;
  25616. }
  25617. }
  25618. }
  25619. }
  25620. // Post-processes
  25621. if (this.activeCameras && this.activeCameras.length > 0) {
  25622. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25623. var camera = _e[_d];
  25624. if (!camera.isReady(true)) {
  25625. return false;
  25626. }
  25627. }
  25628. }
  25629. else if (this.activeCamera) {
  25630. if (!this.activeCamera.isReady(true)) {
  25631. return false;
  25632. }
  25633. }
  25634. // Particles
  25635. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25636. var particleSystem = _g[_f];
  25637. if (!particleSystem.isReady()) {
  25638. return false;
  25639. }
  25640. }
  25641. return true;
  25642. };
  25643. /** Resets all cached information relative to material (including effect and visibility) */
  25644. Scene.prototype.resetCachedMaterial = function () {
  25645. this._cachedMaterial = null;
  25646. this._cachedEffect = null;
  25647. this._cachedVisibility = null;
  25648. };
  25649. /**
  25650. * Registers a function to be called before every frame render
  25651. * @param func defines the function to register
  25652. */
  25653. Scene.prototype.registerBeforeRender = function (func) {
  25654. this.onBeforeRenderObservable.add(func);
  25655. };
  25656. /**
  25657. * Unregisters a function called before every frame render
  25658. * @param func defines the function to unregister
  25659. */
  25660. Scene.prototype.unregisterBeforeRender = function (func) {
  25661. this.onBeforeRenderObservable.removeCallback(func);
  25662. };
  25663. /**
  25664. * Registers a function to be called after every frame render
  25665. * @param func defines the function to register
  25666. */
  25667. Scene.prototype.registerAfterRender = function (func) {
  25668. this.onAfterRenderObservable.add(func);
  25669. };
  25670. /**
  25671. * Unregisters a function called after every frame render
  25672. * @param func defines the function to unregister
  25673. */
  25674. Scene.prototype.unregisterAfterRender = function (func) {
  25675. this.onAfterRenderObservable.removeCallback(func);
  25676. };
  25677. Scene.prototype._executeOnceBeforeRender = function (func) {
  25678. var _this = this;
  25679. var execFunc = function () {
  25680. func();
  25681. setTimeout(function () {
  25682. _this.unregisterBeforeRender(execFunc);
  25683. });
  25684. };
  25685. this.registerBeforeRender(execFunc);
  25686. };
  25687. /**
  25688. * The provided function will run before render once and will be disposed afterwards.
  25689. * A timeout delay can be provided so that the function will be executed in N ms.
  25690. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25691. * @param func The function to be executed.
  25692. * @param timeout optional delay in ms
  25693. */
  25694. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25695. var _this = this;
  25696. if (timeout !== undefined) {
  25697. setTimeout(function () {
  25698. _this._executeOnceBeforeRender(func);
  25699. }, timeout);
  25700. }
  25701. else {
  25702. this._executeOnceBeforeRender(func);
  25703. }
  25704. };
  25705. /** @hidden */
  25706. Scene.prototype._addPendingData = function (data) {
  25707. this._pendingData.push(data);
  25708. };
  25709. /** @hidden */
  25710. Scene.prototype._removePendingData = function (data) {
  25711. var wasLoading = this.isLoading;
  25712. var index = this._pendingData.indexOf(data);
  25713. if (index !== -1) {
  25714. this._pendingData.splice(index, 1);
  25715. }
  25716. if (wasLoading && !this.isLoading) {
  25717. this.onDataLoadedObservable.notifyObservers(this);
  25718. }
  25719. };
  25720. /**
  25721. * Returns the number of items waiting to be loaded
  25722. * @returns the number of items waiting to be loaded
  25723. */
  25724. Scene.prototype.getWaitingItemsCount = function () {
  25725. return this._pendingData.length;
  25726. };
  25727. Object.defineProperty(Scene.prototype, "isLoading", {
  25728. /**
  25729. * Returns a boolean indicating if the scene is still loading data
  25730. */
  25731. get: function () {
  25732. return this._pendingData.length > 0;
  25733. },
  25734. enumerable: true,
  25735. configurable: true
  25736. });
  25737. /**
  25738. * Registers a function to be executed when the scene is ready
  25739. * @param {Function} func - the function to be executed
  25740. */
  25741. Scene.prototype.executeWhenReady = function (func) {
  25742. var _this = this;
  25743. this.onReadyObservable.add(func);
  25744. if (this._executeWhenReadyTimeoutId !== -1) {
  25745. return;
  25746. }
  25747. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25748. _this._checkIsReady();
  25749. }, 150);
  25750. };
  25751. /**
  25752. * Returns a promise that resolves when the scene is ready
  25753. * @returns A promise that resolves when the scene is ready
  25754. */
  25755. Scene.prototype.whenReadyAsync = function () {
  25756. var _this = this;
  25757. return new Promise(function (resolve) {
  25758. _this.executeWhenReady(function () {
  25759. resolve();
  25760. });
  25761. });
  25762. };
  25763. /** @hidden */
  25764. Scene.prototype._checkIsReady = function () {
  25765. var _this = this;
  25766. if (this.isReady()) {
  25767. this.onReadyObservable.notifyObservers(this);
  25768. this.onReadyObservable.clear();
  25769. this._executeWhenReadyTimeoutId = -1;
  25770. return;
  25771. }
  25772. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25773. _this._checkIsReady();
  25774. }, 150);
  25775. };
  25776. // Animations
  25777. /**
  25778. * Will start the animation sequence of a given target
  25779. * @param target defines the target
  25780. * @param from defines from which frame should animation start
  25781. * @param to defines until which frame should animation run.
  25782. * @param weight defines the weight to apply to the animation (1.0 by default)
  25783. * @param loop defines if the animation loops
  25784. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25785. * @param onAnimationEnd defines the function to be executed when the animation ends
  25786. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25787. * @returns the animatable object created for this animation
  25788. */
  25789. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25790. if (weight === void 0) { weight = 1.0; }
  25791. if (speedRatio === void 0) { speedRatio = 1.0; }
  25792. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25793. returnedAnimatable.weight = weight;
  25794. return returnedAnimatable;
  25795. };
  25796. /**
  25797. * Will start the animation sequence of a given target
  25798. * @param target defines the target
  25799. * @param from defines from which frame should animation start
  25800. * @param to defines until which frame should animation run.
  25801. * @param loop defines if the animation loops
  25802. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25803. * @param onAnimationEnd defines the function to be executed when the animation ends
  25804. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25805. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25806. * @returns the animatable object created for this animation
  25807. */
  25808. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25809. if (speedRatio === void 0) { speedRatio = 1.0; }
  25810. if (stopCurrent === void 0) { stopCurrent = true; }
  25811. if (from > to && speedRatio > 0) {
  25812. speedRatio *= -1;
  25813. }
  25814. if (stopCurrent) {
  25815. this.stopAnimation(target);
  25816. }
  25817. if (!animatable) {
  25818. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25819. }
  25820. // Local animations
  25821. if (target.animations) {
  25822. animatable.appendAnimations(target, target.animations);
  25823. }
  25824. // Children animations
  25825. if (target.getAnimatables) {
  25826. var animatables = target.getAnimatables();
  25827. for (var index = 0; index < animatables.length; index++) {
  25828. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25829. }
  25830. }
  25831. animatable.reset();
  25832. return animatable;
  25833. };
  25834. /**
  25835. * Begin a new animation on a given node
  25836. * @param target defines the target where the animation will take place
  25837. * @param animations defines the list of animations to start
  25838. * @param from defines the initial value
  25839. * @param to defines the final value
  25840. * @param loop defines if you want animation to loop (off by default)
  25841. * @param speedRatio defines the speed ratio to apply to all animations
  25842. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25843. * @returns the list of created animatables
  25844. */
  25845. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25846. if (speedRatio === undefined) {
  25847. speedRatio = 1.0;
  25848. }
  25849. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25850. return animatable;
  25851. };
  25852. /**
  25853. * Begin a new animation on a given node and its hierarchy
  25854. * @param target defines the root node where the animation will take place
  25855. * @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.
  25856. * @param animations defines the list of animations to start
  25857. * @param from defines the initial value
  25858. * @param to defines the final value
  25859. * @param loop defines if you want animation to loop (off by default)
  25860. * @param speedRatio defines the speed ratio to apply to all animations
  25861. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25862. * @returns the list of animatables created for all nodes
  25863. */
  25864. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25865. var children = target.getDescendants(directDescendantsOnly);
  25866. var result = [];
  25867. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25868. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25869. var child = children_1[_i];
  25870. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25871. }
  25872. return result;
  25873. };
  25874. /**
  25875. * Gets the animatable associated with a specific target
  25876. * @param target defines the target of the animatable
  25877. * @returns the required animatable if found
  25878. */
  25879. Scene.prototype.getAnimatableByTarget = function (target) {
  25880. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25881. if (this._activeAnimatables[index].target === target) {
  25882. return this._activeAnimatables[index];
  25883. }
  25884. }
  25885. return null;
  25886. };
  25887. /**
  25888. * Gets all animatables associated with a given target
  25889. * @param target defines the target to look animatables for
  25890. * @returns an array of Animatables
  25891. */
  25892. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25893. var result = [];
  25894. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25895. if (this._activeAnimatables[index].target === target) {
  25896. result.push(this._activeAnimatables[index]);
  25897. }
  25898. }
  25899. return result;
  25900. };
  25901. Object.defineProperty(Scene.prototype, "animatables", {
  25902. /**
  25903. * Gets all animatable attached to the scene
  25904. */
  25905. get: function () {
  25906. return this._activeAnimatables;
  25907. },
  25908. enumerable: true,
  25909. configurable: true
  25910. });
  25911. /**
  25912. * Will stop the animation of the given target
  25913. * @param target - the target
  25914. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25915. */
  25916. Scene.prototype.stopAnimation = function (target, animationName) {
  25917. var animatables = this.getAllAnimatablesByTarget(target);
  25918. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25919. var animatable = animatables_1[_i];
  25920. animatable.stop(animationName);
  25921. }
  25922. };
  25923. /**
  25924. * Stops and removes all animations that have been applied to the scene
  25925. */
  25926. Scene.prototype.stopAllAnimations = function () {
  25927. if (this._activeAnimatables) {
  25928. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25929. this._activeAnimatables[i].stop();
  25930. }
  25931. this._activeAnimatables = [];
  25932. }
  25933. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25934. var group = _a[_i];
  25935. group.stop();
  25936. }
  25937. };
  25938. Scene.prototype._animate = function () {
  25939. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25940. return;
  25941. }
  25942. // Getting time
  25943. var now = BABYLON.Tools.Now;
  25944. if (!this._animationTimeLast) {
  25945. if (this._pendingData.length > 0) {
  25946. return;
  25947. }
  25948. this._animationTimeLast = now;
  25949. }
  25950. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25951. this._animationTime += deltaTime;
  25952. this._animationTimeLast = now;
  25953. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25954. this._activeAnimatables[index]._animate(this._animationTime);
  25955. }
  25956. // Late animation bindings
  25957. this._processLateAnimationBindings();
  25958. };
  25959. /** @hidden */
  25960. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25961. var target = runtimeAnimation.target;
  25962. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25963. if (!target._lateAnimationHolders) {
  25964. target._lateAnimationHolders = {};
  25965. }
  25966. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25967. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25968. totalWeight: 0,
  25969. animations: [],
  25970. originalValue: originalValue
  25971. };
  25972. }
  25973. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25974. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25975. };
  25976. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25977. var normalizer = 1.0;
  25978. var finalPosition = BABYLON.Tmp.Vector3[0];
  25979. var finalScaling = BABYLON.Tmp.Vector3[1];
  25980. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25981. var startIndex = 0;
  25982. var originalAnimation = holder.animations[0];
  25983. var originalValue = holder.originalValue;
  25984. var scale = 1;
  25985. if (holder.totalWeight < 1.0) {
  25986. // We need to mix the original value in
  25987. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25988. scale = 1.0 - holder.totalWeight;
  25989. }
  25990. else {
  25991. startIndex = 1;
  25992. // We need to normalize the weights
  25993. normalizer = holder.totalWeight;
  25994. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25995. scale = originalAnimation.weight / normalizer;
  25996. if (scale == 1) {
  25997. return originalAnimation.currentValue;
  25998. }
  25999. }
  26000. finalScaling.scaleInPlace(scale);
  26001. finalPosition.scaleInPlace(scale);
  26002. finalQuaternion.scaleInPlace(scale);
  26003. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26004. var runtimeAnimation = holder.animations[animIndex];
  26005. var scale = runtimeAnimation.weight / normalizer;
  26006. var currentPosition = BABYLON.Tmp.Vector3[2];
  26007. var currentScaling = BABYLON.Tmp.Vector3[3];
  26008. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26009. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26010. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26011. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26012. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26013. }
  26014. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26015. return originalAnimation._workValue;
  26016. };
  26017. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26018. var originalAnimation = holder.animations[0];
  26019. var originalValue = holder.originalValue;
  26020. if (holder.animations.length === 1) {
  26021. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26022. }
  26023. var normalizer = 1.0;
  26024. var quaternions;
  26025. var weights;
  26026. if (holder.totalWeight < 1.0) {
  26027. var scale = 1.0 - holder.totalWeight;
  26028. quaternions = [];
  26029. weights = [];
  26030. quaternions.push(originalValue);
  26031. weights.push(scale);
  26032. }
  26033. else {
  26034. if (holder.animations.length === 2) { // Slerp as soon as we can
  26035. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26036. }
  26037. quaternions = [];
  26038. weights = [];
  26039. normalizer = holder.totalWeight;
  26040. }
  26041. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26042. var runtimeAnimation = holder.animations[animIndex];
  26043. quaternions.push(runtimeAnimation.currentValue);
  26044. weights.push(runtimeAnimation.weight / normalizer);
  26045. }
  26046. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26047. var cumulativeAmount = 0;
  26048. var cumulativeQuaternion = null;
  26049. for (var index = 0; index < quaternions.length;) {
  26050. if (!cumulativeQuaternion) {
  26051. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26052. cumulativeAmount = weights[index] + weights[index + 1];
  26053. index += 2;
  26054. continue;
  26055. }
  26056. cumulativeAmount += weights[index];
  26057. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26058. index++;
  26059. }
  26060. return cumulativeQuaternion;
  26061. };
  26062. Scene.prototype._processLateAnimationBindings = function () {
  26063. if (!this._registeredForLateAnimationBindings.length) {
  26064. return;
  26065. }
  26066. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26067. var target = this._registeredForLateAnimationBindings.data[index];
  26068. for (var path in target._lateAnimationHolders) {
  26069. var holder = target._lateAnimationHolders[path];
  26070. var originalAnimation = holder.animations[0];
  26071. var originalValue = holder.originalValue;
  26072. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26073. var finalValue = void 0;
  26074. if (matrixDecomposeMode) {
  26075. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26076. }
  26077. else {
  26078. var quaternionMode = originalValue.w !== undefined;
  26079. if (quaternionMode) {
  26080. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26081. }
  26082. else {
  26083. var startIndex = 0;
  26084. var normalizer = 1.0;
  26085. if (holder.totalWeight < 1.0) {
  26086. // We need to mix the original value in
  26087. if (originalValue.scale) {
  26088. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26089. }
  26090. else {
  26091. finalValue = originalValue * (1.0 - holder.totalWeight);
  26092. }
  26093. }
  26094. else {
  26095. // We need to normalize the weights
  26096. normalizer = holder.totalWeight;
  26097. var scale_1 = originalAnimation.weight / normalizer;
  26098. if (scale_1 !== 1) {
  26099. if (originalAnimation.currentValue.scale) {
  26100. finalValue = originalAnimation.currentValue.scale(scale_1);
  26101. }
  26102. else {
  26103. finalValue = originalAnimation.currentValue * scale_1;
  26104. }
  26105. }
  26106. else {
  26107. finalValue = originalAnimation.currentValue;
  26108. }
  26109. startIndex = 1;
  26110. }
  26111. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26112. var runtimeAnimation = holder.animations[animIndex];
  26113. var scale = runtimeAnimation.weight / normalizer;
  26114. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26115. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26116. }
  26117. else {
  26118. finalValue += runtimeAnimation.currentValue * scale;
  26119. }
  26120. }
  26121. }
  26122. }
  26123. target[path] = finalValue;
  26124. }
  26125. target._lateAnimationHolders = {};
  26126. }
  26127. this._registeredForLateAnimationBindings.reset();
  26128. };
  26129. // Matrix
  26130. /** @hidden */
  26131. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26132. this._useAlternateCameraConfiguration = active;
  26133. };
  26134. /**
  26135. * Gets the current view matrix
  26136. * @returns a Matrix
  26137. */
  26138. Scene.prototype.getViewMatrix = function () {
  26139. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26140. };
  26141. /**
  26142. * Gets the current projection matrix
  26143. * @returns a Matrix
  26144. */
  26145. Scene.prototype.getProjectionMatrix = function () {
  26146. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26147. };
  26148. /**
  26149. * Gets the current transform matrix
  26150. * @returns a Matrix made of View * Projection
  26151. */
  26152. Scene.prototype.getTransformMatrix = function () {
  26153. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26154. };
  26155. /**
  26156. * Sets the current transform matrix
  26157. * @param view defines the View matrix to use
  26158. * @param projection defines the Projection matrix to use
  26159. */
  26160. Scene.prototype.setTransformMatrix = function (view, projection) {
  26161. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26162. return;
  26163. }
  26164. this._viewUpdateFlag = view.updateFlag;
  26165. this._projectionUpdateFlag = projection.updateFlag;
  26166. this._viewMatrix = view;
  26167. this._projectionMatrix = projection;
  26168. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26169. // Update frustum
  26170. if (!this._frustumPlanes) {
  26171. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26172. }
  26173. else {
  26174. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26175. }
  26176. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26177. var otherCamera = this.activeCamera._alternateCamera;
  26178. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26179. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26180. }
  26181. if (this._sceneUbo.useUbo) {
  26182. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26183. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26184. this._sceneUbo.update();
  26185. }
  26186. };
  26187. /** @hidden */
  26188. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26189. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26190. return;
  26191. }
  26192. this._alternateViewUpdateFlag = view.updateFlag;
  26193. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26194. this._alternateViewMatrix = view;
  26195. this._alternateProjectionMatrix = projection;
  26196. if (!this._alternateTransformMatrix) {
  26197. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26198. }
  26199. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26200. if (!this._alternateSceneUbo) {
  26201. this._createAlternateUbo();
  26202. }
  26203. if (this._alternateSceneUbo.useUbo) {
  26204. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26205. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26206. this._alternateSceneUbo.update();
  26207. }
  26208. };
  26209. /**
  26210. * Gets the uniform buffer used to store scene data
  26211. * @returns a UniformBuffer
  26212. */
  26213. Scene.prototype.getSceneUniformBuffer = function () {
  26214. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26215. };
  26216. /**
  26217. * Gets an unique (relatively to the current scene) Id
  26218. * @returns an unique number for the scene
  26219. */
  26220. Scene.prototype.getUniqueId = function () {
  26221. var result = Scene._uniqueIdCounter;
  26222. Scene._uniqueIdCounter++;
  26223. return result;
  26224. };
  26225. /**
  26226. * Add a mesh to the list of scene's meshes
  26227. * @param newMesh defines the mesh to add
  26228. * @param recursive if all child meshes should also be added to the scene
  26229. */
  26230. Scene.prototype.addMesh = function (newMesh, recursive) {
  26231. var _this = this;
  26232. if (recursive === void 0) { recursive = false; }
  26233. this.meshes.push(newMesh);
  26234. //notify the collision coordinator
  26235. if (this.collisionCoordinator) {
  26236. this.collisionCoordinator.onMeshAdded(newMesh);
  26237. }
  26238. newMesh._resyncLightSources();
  26239. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26240. if (recursive) {
  26241. newMesh.getChildMeshes().forEach(function (m) {
  26242. _this.addMesh(m);
  26243. });
  26244. }
  26245. };
  26246. /**
  26247. * Remove a mesh for the list of scene's meshes
  26248. * @param toRemove defines the mesh to remove
  26249. * @param recursive if all child meshes should also be removed from the scene
  26250. * @returns the index where the mesh was in the mesh list
  26251. */
  26252. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26253. var _this = this;
  26254. if (recursive === void 0) { recursive = false; }
  26255. var index = this.meshes.indexOf(toRemove);
  26256. if (index !== -1) {
  26257. // Remove from the scene if mesh found
  26258. this.meshes.splice(index, 1);
  26259. }
  26260. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26261. if (recursive) {
  26262. toRemove.getChildMeshes().forEach(function (m) {
  26263. _this.removeMesh(m);
  26264. });
  26265. }
  26266. return index;
  26267. };
  26268. /**
  26269. * Add a transform node to the list of scene's transform nodes
  26270. * @param newTransformNode defines the transform node to add
  26271. */
  26272. Scene.prototype.addTransformNode = function (newTransformNode) {
  26273. this.transformNodes.push(newTransformNode);
  26274. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26275. };
  26276. /**
  26277. * Remove a transform node for the list of scene's transform nodes
  26278. * @param toRemove defines the transform node to remove
  26279. * @returns the index where the transform node was in the transform node list
  26280. */
  26281. Scene.prototype.removeTransformNode = function (toRemove) {
  26282. var index = this.transformNodes.indexOf(toRemove);
  26283. if (index !== -1) {
  26284. // Remove from the scene if found
  26285. this.transformNodes.splice(index, 1);
  26286. }
  26287. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26288. return index;
  26289. };
  26290. /**
  26291. * Remove a skeleton for the list of scene's skeletons
  26292. * @param toRemove defines the skeleton to remove
  26293. * @returns the index where the skeleton was in the skeleton list
  26294. */
  26295. Scene.prototype.removeSkeleton = function (toRemove) {
  26296. var index = this.skeletons.indexOf(toRemove);
  26297. if (index !== -1) {
  26298. // Remove from the scene if found
  26299. this.skeletons.splice(index, 1);
  26300. }
  26301. return index;
  26302. };
  26303. /**
  26304. * Remove a morph target for the list of scene's morph targets
  26305. * @param toRemove defines the morph target to remove
  26306. * @returns the index where the morph target was in the morph target list
  26307. */
  26308. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26309. var index = this.morphTargetManagers.indexOf(toRemove);
  26310. if (index !== -1) {
  26311. // Remove from the scene if found
  26312. this.morphTargetManagers.splice(index, 1);
  26313. }
  26314. return index;
  26315. };
  26316. /**
  26317. * Remove a light for the list of scene's lights
  26318. * @param toRemove defines the light to remove
  26319. * @returns the index where the light was in the light list
  26320. */
  26321. Scene.prototype.removeLight = function (toRemove) {
  26322. var index = this.lights.indexOf(toRemove);
  26323. if (index !== -1) {
  26324. // Remove from meshes
  26325. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26326. var mesh = _a[_i];
  26327. mesh._removeLightSource(toRemove);
  26328. }
  26329. // Remove from the scene if mesh found
  26330. this.lights.splice(index, 1);
  26331. this.sortLightsByPriority();
  26332. }
  26333. this.onLightRemovedObservable.notifyObservers(toRemove);
  26334. return index;
  26335. };
  26336. /**
  26337. * Remove a camera for the list of scene's cameras
  26338. * @param toRemove defines the camera to remove
  26339. * @returns the index where the camera was in the camera list
  26340. */
  26341. Scene.prototype.removeCamera = function (toRemove) {
  26342. var index = this.cameras.indexOf(toRemove);
  26343. if (index !== -1) {
  26344. // Remove from the scene if mesh found
  26345. this.cameras.splice(index, 1);
  26346. }
  26347. // Remove from activeCameras
  26348. var index2 = this.activeCameras.indexOf(toRemove);
  26349. if (index2 !== -1) {
  26350. // Remove from the scene if mesh found
  26351. this.activeCameras.splice(index2, 1);
  26352. }
  26353. // Reset the activeCamera
  26354. if (this.activeCamera === toRemove) {
  26355. if (this.cameras.length > 0) {
  26356. this.activeCamera = this.cameras[0];
  26357. }
  26358. else {
  26359. this.activeCamera = null;
  26360. }
  26361. }
  26362. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26363. return index;
  26364. };
  26365. /**
  26366. * Remove a particle system for the list of scene's particle systems
  26367. * @param toRemove defines the particle system to remove
  26368. * @returns the index where the particle system was in the particle system list
  26369. */
  26370. Scene.prototype.removeParticleSystem = function (toRemove) {
  26371. var index = this.particleSystems.indexOf(toRemove);
  26372. if (index !== -1) {
  26373. this.particleSystems.splice(index, 1);
  26374. }
  26375. return index;
  26376. };
  26377. /**
  26378. * Remove a animation for the list of scene's animations
  26379. * @param toRemove defines the animation to remove
  26380. * @returns the index where the animation was in the animation list
  26381. */
  26382. Scene.prototype.removeAnimation = function (toRemove) {
  26383. var index = this.animations.indexOf(toRemove);
  26384. if (index !== -1) {
  26385. this.animations.splice(index, 1);
  26386. }
  26387. return index;
  26388. };
  26389. /**
  26390. * Removes the given animation group from this scene.
  26391. * @param toRemove The animation group to remove
  26392. * @returns The index of the removed animation group
  26393. */
  26394. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26395. var index = this.animationGroups.indexOf(toRemove);
  26396. if (index !== -1) {
  26397. this.animationGroups.splice(index, 1);
  26398. }
  26399. return index;
  26400. };
  26401. /**
  26402. * Removes the given multi-material from this scene.
  26403. * @param toRemove The multi-material to remove
  26404. * @returns The index of the removed multi-material
  26405. */
  26406. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26407. var index = this.multiMaterials.indexOf(toRemove);
  26408. if (index !== -1) {
  26409. this.multiMaterials.splice(index, 1);
  26410. }
  26411. return index;
  26412. };
  26413. /**
  26414. * Removes the given material from this scene.
  26415. * @param toRemove The material to remove
  26416. * @returns The index of the removed material
  26417. */
  26418. Scene.prototype.removeMaterial = function (toRemove) {
  26419. var index = this.materials.indexOf(toRemove);
  26420. if (index !== -1) {
  26421. this.materials.splice(index, 1);
  26422. }
  26423. return index;
  26424. };
  26425. /**
  26426. * Removes the given lens flare system from this scene.
  26427. * @param toRemove The lens flare system to remove
  26428. * @returns The index of the removed lens flare system
  26429. */
  26430. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26431. var index = this.lensFlareSystems.indexOf(toRemove);
  26432. if (index !== -1) {
  26433. this.lensFlareSystems.splice(index, 1);
  26434. }
  26435. return index;
  26436. };
  26437. /**
  26438. * Removes the given action manager from this scene.
  26439. * @param toRemove The action manager to remove
  26440. * @returns The index of the removed action manager
  26441. */
  26442. Scene.prototype.removeActionManager = function (toRemove) {
  26443. var index = this._actionManagers.indexOf(toRemove);
  26444. if (index !== -1) {
  26445. this._actionManagers.splice(index, 1);
  26446. }
  26447. return index;
  26448. };
  26449. /**
  26450. * Removes the given effect layer from this scene.
  26451. * @param toRemove defines the effect layer to remove
  26452. * @returns the index of the removed effect layer
  26453. */
  26454. Scene.prototype.removeEffectLayer = function (toRemove) {
  26455. var index = this.effectLayers.indexOf(toRemove);
  26456. if (index !== -1) {
  26457. this.effectLayers.splice(index, 1);
  26458. }
  26459. return index;
  26460. };
  26461. /**
  26462. * Removes the given texture from this scene.
  26463. * @param toRemove The texture to remove
  26464. * @returns The index of the removed texture
  26465. */
  26466. Scene.prototype.removeTexture = function (toRemove) {
  26467. var index = this.textures.indexOf(toRemove);
  26468. if (index !== -1) {
  26469. this.textures.splice(index, 1);
  26470. }
  26471. return index;
  26472. };
  26473. /**
  26474. * Adds the given light to this scene
  26475. * @param newLight The light to add
  26476. */
  26477. Scene.prototype.addLight = function (newLight) {
  26478. this.lights.push(newLight);
  26479. this.sortLightsByPriority();
  26480. // Add light to all meshes (To support if the light is removed and then readded)
  26481. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26482. var mesh = _a[_i];
  26483. if (mesh._lightSources.indexOf(newLight) === -1) {
  26484. mesh._lightSources.push(newLight);
  26485. mesh._resyncLightSources();
  26486. }
  26487. }
  26488. this.onNewLightAddedObservable.notifyObservers(newLight);
  26489. };
  26490. /**
  26491. * Sorts the list list based on light priorities
  26492. */
  26493. Scene.prototype.sortLightsByPriority = function () {
  26494. if (this.requireLightSorting) {
  26495. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26496. }
  26497. };
  26498. /**
  26499. * Adds the given camera to this scene
  26500. * @param newCamera The camera to add
  26501. */
  26502. Scene.prototype.addCamera = function (newCamera) {
  26503. this.cameras.push(newCamera);
  26504. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26505. };
  26506. /**
  26507. * Adds the given skeleton to this scene
  26508. * @param newSkeleton The skeleton to add
  26509. */
  26510. Scene.prototype.addSkeleton = function (newSkeleton) {
  26511. this.skeletons.push(newSkeleton);
  26512. };
  26513. /**
  26514. * Adds the given particle system to this scene
  26515. * @param newParticleSystem The particle system to add
  26516. */
  26517. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26518. this.particleSystems.push(newParticleSystem);
  26519. };
  26520. /**
  26521. * Adds the given animation to this scene
  26522. * @param newAnimation The animation to add
  26523. */
  26524. Scene.prototype.addAnimation = function (newAnimation) {
  26525. this.animations.push(newAnimation);
  26526. };
  26527. /**
  26528. * Adds the given animation group to this scene.
  26529. * @param newAnimationGroup The animation group to add
  26530. */
  26531. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26532. this.animationGroups.push(newAnimationGroup);
  26533. };
  26534. /**
  26535. * Adds the given multi-material to this scene
  26536. * @param newMultiMaterial The multi-material to add
  26537. */
  26538. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26539. this.multiMaterials.push(newMultiMaterial);
  26540. };
  26541. /**
  26542. * Adds the given material to this scene
  26543. * @param newMaterial The material to add
  26544. */
  26545. Scene.prototype.addMaterial = function (newMaterial) {
  26546. this.materials.push(newMaterial);
  26547. };
  26548. /**
  26549. * Adds the given morph target to this scene
  26550. * @param newMorphTargetManager The morph target to add
  26551. */
  26552. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26553. this.morphTargetManagers.push(newMorphTargetManager);
  26554. };
  26555. /**
  26556. * Adds the given geometry to this scene
  26557. * @param newGeometry The geometry to add
  26558. */
  26559. Scene.prototype.addGeometry = function (newGeometry) {
  26560. this._geometries.push(newGeometry);
  26561. };
  26562. /**
  26563. * Adds the given lens flare system to this scene
  26564. * @param newLensFlareSystem The lens flare system to add
  26565. */
  26566. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26567. this.lensFlareSystems.push(newLensFlareSystem);
  26568. };
  26569. /**
  26570. * Adds the given effect layer to this scene
  26571. * @param newEffectLayer defines the effect layer to add
  26572. */
  26573. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26574. this.effectLayers.push(newEffectLayer);
  26575. };
  26576. /**
  26577. * Adds the given action manager to this scene
  26578. * @param newActionManager The action manager to add
  26579. */
  26580. Scene.prototype.addActionManager = function (newActionManager) {
  26581. this._actionManagers.push(newActionManager);
  26582. };
  26583. /**
  26584. * Adds the given texture to this scene.
  26585. * @param newTexture The texture to add
  26586. */
  26587. Scene.prototype.addTexture = function (newTexture) {
  26588. this.textures.push(newTexture);
  26589. };
  26590. /**
  26591. * Switch active camera
  26592. * @param newCamera defines the new active camera
  26593. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26594. */
  26595. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26596. if (attachControl === void 0) { attachControl = true; }
  26597. var canvas = this._engine.getRenderingCanvas();
  26598. if (!canvas) {
  26599. return;
  26600. }
  26601. if (this.activeCamera) {
  26602. this.activeCamera.detachControl(canvas);
  26603. }
  26604. this.activeCamera = newCamera;
  26605. if (attachControl) {
  26606. newCamera.attachControl(canvas);
  26607. }
  26608. };
  26609. /**
  26610. * sets the active camera of the scene using its ID
  26611. * @param id defines the camera's ID
  26612. * @return the new active camera or null if none found.
  26613. */
  26614. Scene.prototype.setActiveCameraByID = function (id) {
  26615. var camera = this.getCameraByID(id);
  26616. if (camera) {
  26617. this.activeCamera = camera;
  26618. return camera;
  26619. }
  26620. return null;
  26621. };
  26622. /**
  26623. * sets the active camera of the scene using its name
  26624. * @param name defines the camera's name
  26625. * @returns the new active camera or null if none found.
  26626. */
  26627. Scene.prototype.setActiveCameraByName = function (name) {
  26628. var camera = this.getCameraByName(name);
  26629. if (camera) {
  26630. this.activeCamera = camera;
  26631. return camera;
  26632. }
  26633. return null;
  26634. };
  26635. /**
  26636. * get an animation group using its name
  26637. * @param name defines the material's name
  26638. * @return the animation group or null if none found.
  26639. */
  26640. Scene.prototype.getAnimationGroupByName = function (name) {
  26641. for (var index = 0; index < this.animationGroups.length; index++) {
  26642. if (this.animationGroups[index].name === name) {
  26643. return this.animationGroups[index];
  26644. }
  26645. }
  26646. return null;
  26647. };
  26648. /**
  26649. * get a material using its id
  26650. * @param id defines the material's ID
  26651. * @return the material or null if none found.
  26652. */
  26653. Scene.prototype.getMaterialByID = function (id) {
  26654. for (var index = 0; index < this.materials.length; index++) {
  26655. if (this.materials[index].id === id) {
  26656. return this.materials[index];
  26657. }
  26658. }
  26659. return null;
  26660. };
  26661. /**
  26662. * Gets a material using its name
  26663. * @param name defines the material's name
  26664. * @return the material or null if none found.
  26665. */
  26666. Scene.prototype.getMaterialByName = function (name) {
  26667. for (var index = 0; index < this.materials.length; index++) {
  26668. if (this.materials[index].name === name) {
  26669. return this.materials[index];
  26670. }
  26671. }
  26672. return null;
  26673. };
  26674. /**
  26675. * Gets a lens flare system using its name
  26676. * @param name defines the name to look for
  26677. * @returns the lens flare system or null if not found
  26678. */
  26679. Scene.prototype.getLensFlareSystemByName = function (name) {
  26680. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26681. if (this.lensFlareSystems[index].name === name) {
  26682. return this.lensFlareSystems[index];
  26683. }
  26684. }
  26685. return null;
  26686. };
  26687. /**
  26688. * Gets a lens flare system using its id
  26689. * @param id defines the id to look for
  26690. * @returns the lens flare system or null if not found
  26691. */
  26692. Scene.prototype.getLensFlareSystemByID = function (id) {
  26693. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26694. if (this.lensFlareSystems[index].id === id) {
  26695. return this.lensFlareSystems[index];
  26696. }
  26697. }
  26698. return null;
  26699. };
  26700. /**
  26701. * Gets a camera using its id
  26702. * @param id defines the id to look for
  26703. * @returns the camera or null if not found
  26704. */
  26705. Scene.prototype.getCameraByID = function (id) {
  26706. for (var index = 0; index < this.cameras.length; index++) {
  26707. if (this.cameras[index].id === id) {
  26708. return this.cameras[index];
  26709. }
  26710. }
  26711. return null;
  26712. };
  26713. /**
  26714. * Gets a camera using its unique id
  26715. * @param uniqueId defines the unique id to look for
  26716. * @returns the camera or null if not found
  26717. */
  26718. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26719. for (var index = 0; index < this.cameras.length; index++) {
  26720. if (this.cameras[index].uniqueId === uniqueId) {
  26721. return this.cameras[index];
  26722. }
  26723. }
  26724. return null;
  26725. };
  26726. /**
  26727. * Gets a camera using its name
  26728. * @param name defines the camera's name
  26729. * @return the camera or null if none found.
  26730. */
  26731. Scene.prototype.getCameraByName = function (name) {
  26732. for (var index = 0; index < this.cameras.length; index++) {
  26733. if (this.cameras[index].name === name) {
  26734. return this.cameras[index];
  26735. }
  26736. }
  26737. return null;
  26738. };
  26739. /**
  26740. * Gets a bone using its id
  26741. * @param id defines the bone's id
  26742. * @return the bone or null if not found
  26743. */
  26744. Scene.prototype.getBoneByID = function (id) {
  26745. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26746. var skeleton = this.skeletons[skeletonIndex];
  26747. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26748. if (skeleton.bones[boneIndex].id === id) {
  26749. return skeleton.bones[boneIndex];
  26750. }
  26751. }
  26752. }
  26753. return null;
  26754. };
  26755. /**
  26756. * Gets a bone using its id
  26757. * @param name defines the bone's name
  26758. * @return the bone or null if not found
  26759. */
  26760. Scene.prototype.getBoneByName = function (name) {
  26761. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26762. var skeleton = this.skeletons[skeletonIndex];
  26763. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26764. if (skeleton.bones[boneIndex].name === name) {
  26765. return skeleton.bones[boneIndex];
  26766. }
  26767. }
  26768. }
  26769. return null;
  26770. };
  26771. /**
  26772. * Gets a light node using its name
  26773. * @param name defines the the light's name
  26774. * @return the light or null if none found.
  26775. */
  26776. Scene.prototype.getLightByName = function (name) {
  26777. for (var index = 0; index < this.lights.length; index++) {
  26778. if (this.lights[index].name === name) {
  26779. return this.lights[index];
  26780. }
  26781. }
  26782. return null;
  26783. };
  26784. /**
  26785. * Gets a light node using its id
  26786. * @param id defines the light's id
  26787. * @return the light or null if none found.
  26788. */
  26789. Scene.prototype.getLightByID = function (id) {
  26790. for (var index = 0; index < this.lights.length; index++) {
  26791. if (this.lights[index].id === id) {
  26792. return this.lights[index];
  26793. }
  26794. }
  26795. return null;
  26796. };
  26797. /**
  26798. * Gets a light node using its scene-generated unique ID
  26799. * @param uniqueId defines the light's unique id
  26800. * @return the light or null if none found.
  26801. */
  26802. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26803. for (var index = 0; index < this.lights.length; index++) {
  26804. if (this.lights[index].uniqueId === uniqueId) {
  26805. return this.lights[index];
  26806. }
  26807. }
  26808. return null;
  26809. };
  26810. /**
  26811. * Gets a particle system by id
  26812. * @param id defines the particle system id
  26813. * @return the corresponding system or null if none found
  26814. */
  26815. Scene.prototype.getParticleSystemByID = function (id) {
  26816. for (var index = 0; index < this.particleSystems.length; index++) {
  26817. if (this.particleSystems[index].id === id) {
  26818. return this.particleSystems[index];
  26819. }
  26820. }
  26821. return null;
  26822. };
  26823. /**
  26824. * Gets a geometry using its ID
  26825. * @param id defines the geometry's id
  26826. * @return the geometry or null if none found.
  26827. */
  26828. Scene.prototype.getGeometryByID = function (id) {
  26829. for (var index = 0; index < this._geometries.length; index++) {
  26830. if (this._geometries[index].id === id) {
  26831. return this._geometries[index];
  26832. }
  26833. }
  26834. return null;
  26835. };
  26836. /**
  26837. * Add a new geometry to this scene
  26838. * @param geometry defines the geometry to be added to the scene.
  26839. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26840. * @return a boolean defining if the geometry was added or not
  26841. */
  26842. Scene.prototype.pushGeometry = function (geometry, force) {
  26843. if (!force && this.getGeometryByID(geometry.id)) {
  26844. return false;
  26845. }
  26846. this._geometries.push(geometry);
  26847. //notify the collision coordinator
  26848. if (this.collisionCoordinator) {
  26849. this.collisionCoordinator.onGeometryAdded(geometry);
  26850. }
  26851. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26852. return true;
  26853. };
  26854. /**
  26855. * Removes an existing geometry
  26856. * @param geometry defines the geometry to be removed from the scene
  26857. * @return a boolean defining if the geometry was removed or not
  26858. */
  26859. Scene.prototype.removeGeometry = function (geometry) {
  26860. var index = this._geometries.indexOf(geometry);
  26861. if (index > -1) {
  26862. this._geometries.splice(index, 1);
  26863. //notify the collision coordinator
  26864. if (this.collisionCoordinator) {
  26865. this.collisionCoordinator.onGeometryDeleted(geometry);
  26866. }
  26867. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26868. return true;
  26869. }
  26870. return false;
  26871. };
  26872. /**
  26873. * Gets the list of geometries attached to the scene
  26874. * @returns an array of Geometry
  26875. */
  26876. Scene.prototype.getGeometries = function () {
  26877. return this._geometries;
  26878. };
  26879. /**
  26880. * Gets the first added mesh found of a given ID
  26881. * @param id defines the id to search for
  26882. * @return the mesh found or null if not found at all
  26883. */
  26884. Scene.prototype.getMeshByID = function (id) {
  26885. for (var index = 0; index < this.meshes.length; index++) {
  26886. if (this.meshes[index].id === id) {
  26887. return this.meshes[index];
  26888. }
  26889. }
  26890. return null;
  26891. };
  26892. /**
  26893. * Gets a list of meshes using their id
  26894. * @param id defines the id to search for
  26895. * @returns a list of meshes
  26896. */
  26897. Scene.prototype.getMeshesByID = function (id) {
  26898. return this.meshes.filter(function (m) {
  26899. return m.id === id;
  26900. });
  26901. };
  26902. /**
  26903. * Gets the first added transform node found of a given ID
  26904. * @param id defines the id to search for
  26905. * @return the found transform node or null if not found at all.
  26906. */
  26907. Scene.prototype.getTransformNodeByID = function (id) {
  26908. for (var index = 0; index < this.transformNodes.length; index++) {
  26909. if (this.transformNodes[index].id === id) {
  26910. return this.transformNodes[index];
  26911. }
  26912. }
  26913. return null;
  26914. };
  26915. /**
  26916. * Gets a list of transform nodes using their id
  26917. * @param id defines the id to search for
  26918. * @returns a list of transform nodes
  26919. */
  26920. Scene.prototype.getTransformNodesByID = function (id) {
  26921. return this.transformNodes.filter(function (m) {
  26922. return m.id === id;
  26923. });
  26924. };
  26925. /**
  26926. * Gets a mesh with its auto-generated unique id
  26927. * @param uniqueId defines the unique id to search for
  26928. * @return the found mesh or null if not found at all.
  26929. */
  26930. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26931. for (var index = 0; index < this.meshes.length; index++) {
  26932. if (this.meshes[index].uniqueId === uniqueId) {
  26933. return this.meshes[index];
  26934. }
  26935. }
  26936. return null;
  26937. };
  26938. /**
  26939. * Gets a the last added mesh using a given id
  26940. * @param id defines the id to search for
  26941. * @return the found mesh or null if not found at all.
  26942. */
  26943. Scene.prototype.getLastMeshByID = function (id) {
  26944. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26945. if (this.meshes[index].id === id) {
  26946. return this.meshes[index];
  26947. }
  26948. }
  26949. return null;
  26950. };
  26951. /**
  26952. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26953. * @param id defines the id to search for
  26954. * @return the found node or null if not found at all
  26955. */
  26956. Scene.prototype.getLastEntryByID = function (id) {
  26957. var index;
  26958. for (index = this.meshes.length - 1; index >= 0; index--) {
  26959. if (this.meshes[index].id === id) {
  26960. return this.meshes[index];
  26961. }
  26962. }
  26963. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26964. if (this.transformNodes[index].id === id) {
  26965. return this.transformNodes[index];
  26966. }
  26967. }
  26968. for (index = this.cameras.length - 1; index >= 0; index--) {
  26969. if (this.cameras[index].id === id) {
  26970. return this.cameras[index];
  26971. }
  26972. }
  26973. for (index = this.lights.length - 1; index >= 0; index--) {
  26974. if (this.lights[index].id === id) {
  26975. return this.lights[index];
  26976. }
  26977. }
  26978. return null;
  26979. };
  26980. /**
  26981. * Gets a node (Mesh, Camera, Light) using a given id
  26982. * @param id defines the id to search for
  26983. * @return the found node or null if not found at all
  26984. */
  26985. Scene.prototype.getNodeByID = function (id) {
  26986. var mesh = this.getMeshByID(id);
  26987. if (mesh) {
  26988. return mesh;
  26989. }
  26990. var light = this.getLightByID(id);
  26991. if (light) {
  26992. return light;
  26993. }
  26994. var camera = this.getCameraByID(id);
  26995. if (camera) {
  26996. return camera;
  26997. }
  26998. var bone = this.getBoneByID(id);
  26999. return bone;
  27000. };
  27001. /**
  27002. * Gets a node (Mesh, Camera, Light) using a given name
  27003. * @param name defines the name to search for
  27004. * @return the found node or null if not found at all.
  27005. */
  27006. Scene.prototype.getNodeByName = function (name) {
  27007. var mesh = this.getMeshByName(name);
  27008. if (mesh) {
  27009. return mesh;
  27010. }
  27011. var light = this.getLightByName(name);
  27012. if (light) {
  27013. return light;
  27014. }
  27015. var camera = this.getCameraByName(name);
  27016. if (camera) {
  27017. return camera;
  27018. }
  27019. var bone = this.getBoneByName(name);
  27020. return bone;
  27021. };
  27022. /**
  27023. * Gets a mesh using a given name
  27024. * @param name defines the name to search for
  27025. * @return the found mesh or null if not found at all.
  27026. */
  27027. Scene.prototype.getMeshByName = function (name) {
  27028. for (var index = 0; index < this.meshes.length; index++) {
  27029. if (this.meshes[index].name === name) {
  27030. return this.meshes[index];
  27031. }
  27032. }
  27033. return null;
  27034. };
  27035. /**
  27036. * Gets a transform node using a given name
  27037. * @param name defines the name to search for
  27038. * @return the found transform node or null if not found at all.
  27039. */
  27040. Scene.prototype.getTransformNodeByName = function (name) {
  27041. for (var index = 0; index < this.transformNodes.length; index++) {
  27042. if (this.transformNodes[index].name === name) {
  27043. return this.transformNodes[index];
  27044. }
  27045. }
  27046. return null;
  27047. };
  27048. /**
  27049. * Gets a sound using a given name
  27050. * @param name defines the name to search for
  27051. * @return the found sound or null if not found at all.
  27052. */
  27053. Scene.prototype.getSoundByName = function (name) {
  27054. var index;
  27055. if (BABYLON.AudioEngine) {
  27056. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27057. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27058. return this.mainSoundTrack.soundCollection[index];
  27059. }
  27060. }
  27061. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27062. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27063. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27064. return this.soundTracks[sdIndex].soundCollection[index];
  27065. }
  27066. }
  27067. }
  27068. }
  27069. return null;
  27070. };
  27071. /**
  27072. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27073. * @param id defines the id to search for
  27074. * @return the found skeleton or null if not found at all.
  27075. */
  27076. Scene.prototype.getLastSkeletonByID = function (id) {
  27077. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27078. if (this.skeletons[index].id === id) {
  27079. return this.skeletons[index];
  27080. }
  27081. }
  27082. return null;
  27083. };
  27084. /**
  27085. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27086. * @param id defines the id to search for
  27087. * @return the found skeleton or null if not found at all.
  27088. */
  27089. Scene.prototype.getSkeletonById = function (id) {
  27090. for (var index = 0; index < this.skeletons.length; index++) {
  27091. if (this.skeletons[index].id === id) {
  27092. return this.skeletons[index];
  27093. }
  27094. }
  27095. return null;
  27096. };
  27097. /**
  27098. * Gets a skeleton using a given name
  27099. * @param name defines the name to search for
  27100. * @return the found skeleton or null if not found at all.
  27101. */
  27102. Scene.prototype.getSkeletonByName = function (name) {
  27103. for (var index = 0; index < this.skeletons.length; index++) {
  27104. if (this.skeletons[index].name === name) {
  27105. return this.skeletons[index];
  27106. }
  27107. }
  27108. return null;
  27109. };
  27110. /**
  27111. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27112. * @param id defines the id to search for
  27113. * @return the found morph target manager or null if not found at all.
  27114. */
  27115. Scene.prototype.getMorphTargetManagerById = function (id) {
  27116. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27117. if (this.morphTargetManagers[index].uniqueId === id) {
  27118. return this.morphTargetManagers[index];
  27119. }
  27120. }
  27121. return null;
  27122. };
  27123. /**
  27124. * Gets a boolean indicating if the given mesh is active
  27125. * @param mesh defines the mesh to look for
  27126. * @returns true if the mesh is in the active list
  27127. */
  27128. Scene.prototype.isActiveMesh = function (mesh) {
  27129. return (this._activeMeshes.indexOf(mesh) !== -1);
  27130. };
  27131. /**
  27132. * Return a the first highlight layer of the scene with a given name.
  27133. * @param name The name of the highlight layer to look for.
  27134. * @return The highlight layer if found otherwise null.
  27135. */
  27136. Scene.prototype.getHighlightLayerByName = function (name) {
  27137. for (var index = 0; index < this.effectLayers.length; index++) {
  27138. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27139. return this.effectLayers[index];
  27140. }
  27141. }
  27142. return null;
  27143. };
  27144. /**
  27145. * Return a the first highlight layer of the scene with a given name.
  27146. * @param name The name of the highlight layer to look for.
  27147. * @return The highlight layer if found otherwise null.
  27148. */
  27149. Scene.prototype.getGlowLayerByName = function (name) {
  27150. for (var index = 0; index < this.effectLayers.length; index++) {
  27151. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27152. return this.effectLayers[index];
  27153. }
  27154. }
  27155. return null;
  27156. };
  27157. Object.defineProperty(Scene.prototype, "uid", {
  27158. /**
  27159. * Return a unique id as a string which can serve as an identifier for the scene
  27160. */
  27161. get: function () {
  27162. if (!this._uid) {
  27163. this._uid = BABYLON.Tools.RandomId();
  27164. }
  27165. return this._uid;
  27166. },
  27167. enumerable: true,
  27168. configurable: true
  27169. });
  27170. /**
  27171. * Add an externaly attached data from its key.
  27172. * This method call will fail and return false, if such key already exists.
  27173. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27174. * @param key the unique key that identifies the data
  27175. * @param data the data object to associate to the key for this Engine instance
  27176. * @return true if no such key were already present and the data was added successfully, false otherwise
  27177. */
  27178. Scene.prototype.addExternalData = function (key, data) {
  27179. if (!this._externalData) {
  27180. this._externalData = new BABYLON.StringDictionary();
  27181. }
  27182. return this._externalData.add(key, data);
  27183. };
  27184. /**
  27185. * Get an externaly attached data from its key
  27186. * @param key the unique key that identifies the data
  27187. * @return the associated data, if present (can be null), or undefined if not present
  27188. */
  27189. Scene.prototype.getExternalData = function (key) {
  27190. if (!this._externalData) {
  27191. return null;
  27192. }
  27193. return this._externalData.get(key);
  27194. };
  27195. /**
  27196. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27197. * @param key the unique key that identifies the data
  27198. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27199. * @return the associated data, can be null if the factory returned null.
  27200. */
  27201. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27202. if (!this._externalData) {
  27203. this._externalData = new BABYLON.StringDictionary();
  27204. }
  27205. return this._externalData.getOrAddWithFactory(key, factory);
  27206. };
  27207. /**
  27208. * Remove an externaly attached data from the Engine instance
  27209. * @param key the unique key that identifies the data
  27210. * @return true if the data was successfully removed, false if it doesn't exist
  27211. */
  27212. Scene.prototype.removeExternalData = function (key) {
  27213. return this._externalData.remove(key);
  27214. };
  27215. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27216. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27217. if (mesh.showSubMeshesBoundingBox) {
  27218. var boundingInfo = subMesh.getBoundingInfo();
  27219. if (boundingInfo !== null && boundingInfo !== undefined) {
  27220. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27221. }
  27222. }
  27223. var material = subMesh.getMaterial();
  27224. if (material !== null && material !== undefined) {
  27225. // Render targets
  27226. if (material.getRenderTargetTextures !== undefined) {
  27227. if (this._processedMaterials.indexOf(material) === -1) {
  27228. this._processedMaterials.push(material);
  27229. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27230. }
  27231. }
  27232. // Dispatch
  27233. this._activeIndices.addCount(subMesh.indexCount, false);
  27234. this._renderingManager.dispatch(subMesh, mesh, material);
  27235. }
  27236. }
  27237. };
  27238. /**
  27239. * Clear the processed materials smart array preventing retention point in material dispose.
  27240. */
  27241. Scene.prototype.freeProcessedMaterials = function () {
  27242. this._processedMaterials.dispose();
  27243. };
  27244. /**
  27245. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27246. */
  27247. Scene.prototype.freeActiveMeshes = function () {
  27248. this._activeMeshes.dispose();
  27249. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27250. this.activeCamera._activeMeshes.dispose();
  27251. }
  27252. if (this.activeCameras) {
  27253. for (var i = 0; i < this.activeCameras.length; i++) {
  27254. var activeCamera = this.activeCameras[i];
  27255. if (activeCamera && activeCamera._activeMeshes) {
  27256. activeCamera._activeMeshes.dispose();
  27257. }
  27258. }
  27259. }
  27260. };
  27261. /**
  27262. * Clear the info related to rendering groups preventing retention points during dispose.
  27263. */
  27264. Scene.prototype.freeRenderingGroups = function () {
  27265. if (this._renderingManager) {
  27266. this._renderingManager.freeRenderingGroups();
  27267. }
  27268. if (this.textures) {
  27269. for (var i = 0; i < this.textures.length; i++) {
  27270. var texture = this.textures[i];
  27271. if (texture && texture.renderList) {
  27272. texture.freeRenderingGroups();
  27273. }
  27274. }
  27275. }
  27276. };
  27277. /** @hidden */
  27278. Scene.prototype._isInIntermediateRendering = function () {
  27279. return this._intermediateRendering;
  27280. };
  27281. /**
  27282. * Defines the current active mesh candidate provider
  27283. * @param provider defines the provider to use
  27284. */
  27285. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27286. this._activeMeshCandidateProvider = provider;
  27287. };
  27288. /**
  27289. * Gets the current active mesh candidate provider
  27290. * @returns the current active mesh candidate provider
  27291. */
  27292. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27293. return this._activeMeshCandidateProvider;
  27294. };
  27295. /**
  27296. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27297. * @returns the current scene
  27298. */
  27299. Scene.prototype.freezeActiveMeshes = function () {
  27300. if (!this.activeCamera) {
  27301. return this;
  27302. }
  27303. if (!this._frustumPlanes) {
  27304. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27305. }
  27306. this._evaluateActiveMeshes();
  27307. this._activeMeshesFrozen = true;
  27308. return this;
  27309. };
  27310. /**
  27311. * Use this function to restart evaluating active meshes on every frame
  27312. * @returns the current scene
  27313. */
  27314. Scene.prototype.unfreezeActiveMeshes = function () {
  27315. this._activeMeshesFrozen = false;
  27316. return this;
  27317. };
  27318. Scene.prototype._evaluateActiveMeshes = function () {
  27319. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27320. return;
  27321. }
  27322. if (!this.activeCamera) {
  27323. return;
  27324. }
  27325. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27326. this.activeCamera._activeMeshes.reset();
  27327. this._activeMeshes.reset();
  27328. this._renderingManager.reset();
  27329. this._processedMaterials.reset();
  27330. this._activeParticleSystems.reset();
  27331. this._activeSkeletons.reset();
  27332. this._softwareSkinnedMeshes.reset();
  27333. if (this._boundingBoxRenderer) {
  27334. this._boundingBoxRenderer.reset();
  27335. }
  27336. // Meshes
  27337. var meshes;
  27338. var len;
  27339. var checkIsEnabled = true;
  27340. // Determine mesh candidates
  27341. if (this._activeMeshCandidateProvider !== undefined) {
  27342. // Use _activeMeshCandidateProvider
  27343. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27344. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27345. if (meshes !== undefined) {
  27346. len = meshes.length;
  27347. }
  27348. else {
  27349. len = 0;
  27350. }
  27351. }
  27352. else if (this._selectionOctree !== undefined) {
  27353. // Octree
  27354. var selection = this._selectionOctree.select(this._frustumPlanes);
  27355. meshes = selection.data;
  27356. len = selection.length;
  27357. }
  27358. else {
  27359. // Full scene traversal
  27360. len = this.meshes.length;
  27361. meshes = this.meshes;
  27362. }
  27363. // Check each mesh
  27364. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27365. mesh = meshes[meshIndex];
  27366. if (mesh.isBlocked) {
  27367. continue;
  27368. }
  27369. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27370. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27371. continue;
  27372. }
  27373. mesh.computeWorldMatrix();
  27374. // Intersections
  27375. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27376. this._meshesForIntersections.pushNoDuplicate(mesh);
  27377. }
  27378. // Switch to current LOD
  27379. meshLOD = mesh.getLOD(this.activeCamera);
  27380. if (meshLOD === undefined || meshLOD === null) {
  27381. continue;
  27382. }
  27383. mesh._preActivate();
  27384. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27385. this._activeMeshes.push(mesh);
  27386. this.activeCamera._activeMeshes.push(mesh);
  27387. mesh._activate(this._renderId);
  27388. if (meshLOD !== mesh) {
  27389. meshLOD._activate(this._renderId);
  27390. }
  27391. this._activeMesh(mesh, meshLOD);
  27392. }
  27393. }
  27394. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27395. // Particle systems
  27396. if (this.particlesEnabled) {
  27397. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27398. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27399. var particleSystem = this.particleSystems[particleIndex];
  27400. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27401. continue;
  27402. }
  27403. var emitter = particleSystem.emitter;
  27404. if (!emitter.position || emitter.isEnabled()) {
  27405. this._activeParticleSystems.push(particleSystem);
  27406. particleSystem.animate();
  27407. this._renderingManager.dispatchParticles(particleSystem);
  27408. }
  27409. }
  27410. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27411. }
  27412. };
  27413. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27414. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27415. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27416. mesh.skeleton.prepare();
  27417. }
  27418. if (!mesh.computeBonesUsingShaders) {
  27419. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27420. }
  27421. }
  27422. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27423. var boundingInfo = sourceMesh.getBoundingInfo();
  27424. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27425. }
  27426. if (mesh !== undefined && mesh !== null
  27427. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27428. // Submeshes Octrees
  27429. var len;
  27430. var subMeshes;
  27431. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27432. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27433. len = intersections.length;
  27434. subMeshes = intersections.data;
  27435. }
  27436. else {
  27437. subMeshes = mesh.subMeshes;
  27438. len = subMeshes.length;
  27439. }
  27440. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27441. subMesh = subMeshes[subIndex];
  27442. this._evaluateSubMesh(subMesh, mesh);
  27443. }
  27444. }
  27445. };
  27446. /**
  27447. * Update the transform matrix to update from the current active camera
  27448. * @param force defines a boolean used to force the update even if cache is up to date
  27449. */
  27450. Scene.prototype.updateTransformMatrix = function (force) {
  27451. if (!this.activeCamera) {
  27452. return;
  27453. }
  27454. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27455. };
  27456. /**
  27457. * 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)
  27458. * @param alternateCamera defines the camera to use
  27459. */
  27460. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27461. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27462. };
  27463. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27464. if (camera && camera._skipRendering) {
  27465. return;
  27466. }
  27467. var engine = this._engine;
  27468. this.activeCamera = camera;
  27469. if (!this.activeCamera)
  27470. throw new Error("Active camera not set");
  27471. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27472. // Viewport
  27473. engine.setViewport(this.activeCamera.viewport);
  27474. // Camera
  27475. this.resetCachedMaterial();
  27476. this._renderId++;
  27477. this.updateTransformMatrix();
  27478. if (camera._alternateCamera) {
  27479. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27480. this._alternateRendering = true;
  27481. }
  27482. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27483. // Meshes
  27484. this._evaluateActiveMeshes();
  27485. // Software skinning
  27486. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27487. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27488. mesh.applySkeleton(mesh.skeleton);
  27489. }
  27490. // Render targets
  27491. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27492. var needsRestoreFrameBuffer = false;
  27493. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27494. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27495. }
  27496. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27497. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27498. }
  27499. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27500. this._intermediateRendering = true;
  27501. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27502. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27503. var renderTarget = this._renderTargets.data[renderIndex];
  27504. if (renderTarget._shouldRender()) {
  27505. this._renderId++;
  27506. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27507. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27508. }
  27509. }
  27510. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27511. this._intermediateRendering = false;
  27512. this._renderId++;
  27513. needsRestoreFrameBuffer = true; // Restore back buffer
  27514. }
  27515. // Render EffecttLayer Texture
  27516. var stencilState = this._engine.getStencilBuffer();
  27517. var renderEffects = false;
  27518. var needStencil = false;
  27519. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27520. this._intermediateRendering = true;
  27521. for (var i = 0; i < this.effectLayers.length; i++) {
  27522. var effectLayer = this.effectLayers[i];
  27523. if (effectLayer.shouldRender() &&
  27524. (!effectLayer.camera ||
  27525. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27526. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27527. renderEffects = true;
  27528. needStencil = needStencil || effectLayer.needStencil();
  27529. var renderTarget = effectLayer._mainTexture;
  27530. if (renderTarget._shouldRender()) {
  27531. this._renderId++;
  27532. renderTarget.render(false, false);
  27533. needsRestoreFrameBuffer = true;
  27534. }
  27535. }
  27536. }
  27537. this._intermediateRendering = false;
  27538. this._renderId++;
  27539. }
  27540. if (needsRestoreFrameBuffer) {
  27541. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27542. }
  27543. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27544. // Prepare Frame
  27545. this.postProcessManager._prepareFrame();
  27546. // Backgrounds
  27547. var layerIndex;
  27548. var layer;
  27549. if (this.layers.length) {
  27550. engine.setDepthBuffer(false);
  27551. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27552. layer = this.layers[layerIndex];
  27553. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27554. layer.render();
  27555. }
  27556. }
  27557. engine.setDepthBuffer(true);
  27558. }
  27559. // Activate effect Layer stencil
  27560. if (needStencil) {
  27561. this._engine.setStencilBuffer(true);
  27562. }
  27563. // Render
  27564. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27565. this._renderingManager.render(null, null, true, true);
  27566. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27567. // Restore effect Layer stencil
  27568. if (needStencil) {
  27569. this._engine.setStencilBuffer(stencilState);
  27570. }
  27571. // Bounding boxes
  27572. if (this._boundingBoxRenderer) {
  27573. this._boundingBoxRenderer.render();
  27574. }
  27575. // Lens flares
  27576. if (this.lensFlaresEnabled) {
  27577. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27578. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27579. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27580. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27581. lensFlareSystem.render();
  27582. }
  27583. }
  27584. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27585. }
  27586. // Effect Layer
  27587. if (renderEffects) {
  27588. engine.setDepthBuffer(false);
  27589. for (var i = 0; i < this.effectLayers.length; i++) {
  27590. if (this.effectLayers[i].shouldRender()) {
  27591. this.effectLayers[i].render();
  27592. }
  27593. }
  27594. engine.setDepthBuffer(true);
  27595. }
  27596. // Foregrounds
  27597. if (this.layers.length) {
  27598. engine.setDepthBuffer(false);
  27599. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27600. layer = this.layers[layerIndex];
  27601. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27602. layer.render();
  27603. }
  27604. }
  27605. engine.setDepthBuffer(true);
  27606. }
  27607. // Finalize frame
  27608. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27609. // Reset some special arrays
  27610. this._renderTargets.reset();
  27611. this._alternateRendering = false;
  27612. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27613. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27614. };
  27615. Scene.prototype._processSubCameras = function (camera) {
  27616. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27617. this._renderForCamera(camera);
  27618. return;
  27619. }
  27620. // rig cameras
  27621. for (var index = 0; index < camera._rigCameras.length; index++) {
  27622. this._renderForCamera(camera._rigCameras[index], camera);
  27623. }
  27624. this.activeCamera = camera;
  27625. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27626. };
  27627. Scene.prototype._checkIntersections = function () {
  27628. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27629. var sourceMesh = this._meshesForIntersections.data[index];
  27630. if (!sourceMesh.actionManager) {
  27631. continue;
  27632. }
  27633. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27634. var action = sourceMesh.actionManager.actions[actionIndex];
  27635. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27636. var parameters = action.getTriggerParameter();
  27637. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27638. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27639. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27640. if (areIntersecting && currentIntersectionInProgress === -1) {
  27641. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27642. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27643. sourceMesh._intersectionsInProgress.push(otherMesh);
  27644. }
  27645. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27646. sourceMesh._intersectionsInProgress.push(otherMesh);
  27647. }
  27648. }
  27649. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27650. //They intersected, and now they don't.
  27651. //is this trigger an exit trigger? execute an event.
  27652. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27653. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27654. }
  27655. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27656. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27657. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27658. return otherMesh === parameterMesh;
  27659. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27660. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27661. }
  27662. }
  27663. }
  27664. }
  27665. }
  27666. };
  27667. /**
  27668. * Render the scene
  27669. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27670. */
  27671. Scene.prototype.render = function (updateCameras) {
  27672. if (updateCameras === void 0) { updateCameras = true; }
  27673. if (this.isDisposed) {
  27674. return;
  27675. }
  27676. this._activeParticles.fetchNewFrame();
  27677. this._totalVertices.fetchNewFrame();
  27678. this._activeIndices.fetchNewFrame();
  27679. this._activeBones.fetchNewFrame();
  27680. this._meshesForIntersections.reset();
  27681. this.resetCachedMaterial();
  27682. this.onBeforeAnimationsObservable.notifyObservers(this);
  27683. // Actions
  27684. if (this.actionManager) {
  27685. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27686. }
  27687. //Simplification Queue
  27688. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27689. this.simplificationQueue.executeNext();
  27690. }
  27691. if (this._engine.isDeterministicLockStep()) {
  27692. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27693. var defaultFPS = (60.0 / 1000.0);
  27694. var defaultFrameTime = 1000 / 60; // frame time in MS
  27695. if (this._physicsEngine) {
  27696. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27697. }
  27698. var stepsTaken = 0;
  27699. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27700. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27701. internalSteps = Math.min(internalSteps, maxSubSteps);
  27702. do {
  27703. this.onBeforeStepObservable.notifyObservers(this);
  27704. // Animations
  27705. this._animationRatio = defaultFrameTime * defaultFPS;
  27706. this._animate();
  27707. this.onAfterAnimationsObservable.notifyObservers(this);
  27708. // Physics
  27709. if (this._physicsEngine) {
  27710. this.onBeforePhysicsObservable.notifyObservers(this);
  27711. this._physicsEngine._step(defaultFrameTime / 1000);
  27712. this.onAfterPhysicsObservable.notifyObservers(this);
  27713. }
  27714. this.onAfterStepObservable.notifyObservers(this);
  27715. this._currentStepId++;
  27716. stepsTaken++;
  27717. deltaTime -= defaultFrameTime;
  27718. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27719. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27720. }
  27721. else {
  27722. // Animations
  27723. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27724. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27725. this._animate();
  27726. this.onAfterAnimationsObservable.notifyObservers(this);
  27727. // Physics
  27728. if (this._physicsEngine) {
  27729. this.onBeforePhysicsObservable.notifyObservers(this);
  27730. this._physicsEngine._step(deltaTime / 1000.0);
  27731. this.onAfterPhysicsObservable.notifyObservers(this);
  27732. }
  27733. }
  27734. // update gamepad manager
  27735. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27736. this._gamepadManager._checkGamepadsStatus();
  27737. }
  27738. // Update Cameras
  27739. if (updateCameras) {
  27740. if (this.activeCameras.length > 0) {
  27741. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27742. var camera = this.activeCameras[cameraIndex];
  27743. camera.update();
  27744. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27745. // rig cameras
  27746. for (var index = 0; index < camera._rigCameras.length; index++) {
  27747. camera._rigCameras[index].update();
  27748. }
  27749. }
  27750. }
  27751. }
  27752. else if (this.activeCamera) {
  27753. this.activeCamera.update();
  27754. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27755. // rig cameras
  27756. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27757. this.activeCamera._rigCameras[index].update();
  27758. }
  27759. }
  27760. }
  27761. }
  27762. // Before render
  27763. this.onBeforeRenderObservable.notifyObservers(this);
  27764. // Customs render targets
  27765. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27766. var engine = this.getEngine();
  27767. var currentActiveCamera = this.activeCamera;
  27768. if (this.renderTargetsEnabled) {
  27769. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27770. this._intermediateRendering = true;
  27771. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27772. var renderTarget = this.customRenderTargets[customIndex];
  27773. if (renderTarget._shouldRender()) {
  27774. this._renderId++;
  27775. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27776. if (!this.activeCamera)
  27777. throw new Error("Active camera not set");
  27778. // Viewport
  27779. engine.setViewport(this.activeCamera.viewport);
  27780. // Camera
  27781. this.updateTransformMatrix();
  27782. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27783. }
  27784. }
  27785. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27786. this._intermediateRendering = false;
  27787. this._renderId++;
  27788. }
  27789. // Restore back buffer
  27790. if (this.customRenderTargets.length > 0) {
  27791. engine.restoreDefaultFramebuffer();
  27792. }
  27793. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27794. this.activeCamera = currentActiveCamera;
  27795. // Procedural textures
  27796. if (this.proceduralTexturesEnabled) {
  27797. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27798. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27799. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27800. if (proceduralTexture._shouldRender()) {
  27801. proceduralTexture.render();
  27802. }
  27803. }
  27804. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27805. }
  27806. // Clear
  27807. if (this.autoClearDepthAndStencil || this.autoClear) {
  27808. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27809. }
  27810. // Shadows
  27811. if (this.shadowsEnabled) {
  27812. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27813. var light = this.lights[lightIndex];
  27814. var shadowGenerator = light.getShadowGenerator();
  27815. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27816. var shadowMap = (shadowGenerator.getShadowMap());
  27817. if (this.textures.indexOf(shadowMap) !== -1) {
  27818. this._renderTargets.push(shadowMap);
  27819. }
  27820. }
  27821. }
  27822. }
  27823. // Depth renderer
  27824. for (var key in this._depthRenderer) {
  27825. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27826. }
  27827. // Geometry renderer
  27828. if (this._geometryBufferRenderer) {
  27829. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27830. }
  27831. // RenderPipeline
  27832. if (this._postProcessRenderPipelineManager) {
  27833. this._postProcessRenderPipelineManager.update();
  27834. }
  27835. // Multi-cameras?
  27836. if (this.activeCameras.length > 0) {
  27837. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27838. if (cameraIndex > 0) {
  27839. this._engine.clear(null, false, true, true);
  27840. }
  27841. this._processSubCameras(this.activeCameras[cameraIndex]);
  27842. }
  27843. }
  27844. else {
  27845. if (!this.activeCamera) {
  27846. throw new Error("No camera defined");
  27847. }
  27848. this._processSubCameras(this.activeCamera);
  27849. }
  27850. // Intersection checks
  27851. this._checkIntersections();
  27852. // Update the audio listener attached to the camera
  27853. if (BABYLON.AudioEngine) {
  27854. this._updateAudioParameters();
  27855. }
  27856. // After render
  27857. if (this.afterRender) {
  27858. this.afterRender();
  27859. }
  27860. this.onAfterRenderObservable.notifyObservers(this);
  27861. // Cleaning
  27862. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27863. var data = this._toBeDisposed.data[index];
  27864. if (data) {
  27865. data.dispose();
  27866. }
  27867. this._toBeDisposed[index] = null;
  27868. }
  27869. this._toBeDisposed.reset();
  27870. if (this.dumpNextRenderTargets) {
  27871. this.dumpNextRenderTargets = false;
  27872. }
  27873. this._activeBones.addCount(0, true);
  27874. this._activeIndices.addCount(0, true);
  27875. this._activeParticles.addCount(0, true);
  27876. };
  27877. Scene.prototype._updateAudioParameters = function () {
  27878. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27879. return;
  27880. }
  27881. var listeningCamera;
  27882. var audioEngine = BABYLON.Engine.audioEngine;
  27883. if (this.activeCameras.length > 0) {
  27884. listeningCamera = this.activeCameras[0];
  27885. }
  27886. else {
  27887. listeningCamera = this.activeCamera;
  27888. }
  27889. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27890. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27891. // for VR cameras
  27892. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27893. listeningCamera = listeningCamera.rigCameras[0];
  27894. }
  27895. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27896. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27897. cameraDirection.normalize();
  27898. // To avoid some errors on GearVR
  27899. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27900. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27901. }
  27902. var i;
  27903. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27904. var sound = this.mainSoundTrack.soundCollection[i];
  27905. if (sound.useCustomAttenuation) {
  27906. sound.updateDistanceFromListener();
  27907. }
  27908. }
  27909. for (i = 0; i < this.soundTracks.length; i++) {
  27910. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27911. sound = this.soundTracks[i].soundCollection[j];
  27912. if (sound.useCustomAttenuation) {
  27913. sound.updateDistanceFromListener();
  27914. }
  27915. }
  27916. }
  27917. }
  27918. };
  27919. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27920. // Audio
  27921. /**
  27922. * Gets or sets if audio support is enabled
  27923. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27924. */
  27925. get: function () {
  27926. return this._audioEnabled;
  27927. },
  27928. set: function (value) {
  27929. this._audioEnabled = value;
  27930. if (BABYLON.AudioEngine) {
  27931. if (this._audioEnabled) {
  27932. this._enableAudio();
  27933. }
  27934. else {
  27935. this._disableAudio();
  27936. }
  27937. }
  27938. },
  27939. enumerable: true,
  27940. configurable: true
  27941. });
  27942. Scene.prototype._disableAudio = function () {
  27943. var i;
  27944. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27945. this.mainSoundTrack.soundCollection[i].pause();
  27946. }
  27947. for (i = 0; i < this.soundTracks.length; i++) {
  27948. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27949. this.soundTracks[i].soundCollection[j].pause();
  27950. }
  27951. }
  27952. };
  27953. Scene.prototype._enableAudio = function () {
  27954. var i;
  27955. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27956. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27957. this.mainSoundTrack.soundCollection[i].play();
  27958. }
  27959. }
  27960. for (i = 0; i < this.soundTracks.length; i++) {
  27961. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27962. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27963. this.soundTracks[i].soundCollection[j].play();
  27964. }
  27965. }
  27966. }
  27967. };
  27968. Object.defineProperty(Scene.prototype, "headphone", {
  27969. /**
  27970. * Gets or sets if audio will be output to headphones
  27971. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27972. */
  27973. get: function () {
  27974. return this._headphone;
  27975. },
  27976. set: function (value) {
  27977. this._headphone = value;
  27978. if (BABYLON.AudioEngine) {
  27979. if (this._headphone) {
  27980. this._switchAudioModeForHeadphones();
  27981. }
  27982. else {
  27983. this._switchAudioModeForNormalSpeakers();
  27984. }
  27985. }
  27986. },
  27987. enumerable: true,
  27988. configurable: true
  27989. });
  27990. Scene.prototype._switchAudioModeForHeadphones = function () {
  27991. this.mainSoundTrack.switchPanningModelToHRTF();
  27992. for (var i = 0; i < this.soundTracks.length; i++) {
  27993. this.soundTracks[i].switchPanningModelToHRTF();
  27994. }
  27995. };
  27996. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27997. this.mainSoundTrack.switchPanningModelToEqualPower();
  27998. for (var i = 0; i < this.soundTracks.length; i++) {
  27999. this.soundTracks[i].switchPanningModelToEqualPower();
  28000. }
  28001. };
  28002. /**
  28003. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28004. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28005. * @returns the created depth renderer
  28006. */
  28007. Scene.prototype.enableDepthRenderer = function (camera) {
  28008. camera = camera || this.activeCamera;
  28009. if (!camera) {
  28010. throw "No camera available to enable depth renderer";
  28011. }
  28012. if (!this._depthRenderer[camera.id]) {
  28013. var textureType = 0;
  28014. if (this._engine.getCaps().textureHalfFloatRender) {
  28015. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28016. }
  28017. else if (this._engine.getCaps().textureFloatRender) {
  28018. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28019. }
  28020. else {
  28021. throw "Depth renderer does not support int texture type";
  28022. }
  28023. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28024. }
  28025. return this._depthRenderer[camera.id];
  28026. };
  28027. /**
  28028. * Disables a depth renderer for a given camera
  28029. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28030. */
  28031. Scene.prototype.disableDepthRenderer = function (camera) {
  28032. camera = camera || this.activeCamera;
  28033. if (!camera || !this._depthRenderer[camera.id]) {
  28034. return;
  28035. }
  28036. this._depthRenderer[camera.id].dispose();
  28037. delete this._depthRenderer[camera.id];
  28038. };
  28039. /**
  28040. * Enables a GeometryBufferRender and associates it with the scene
  28041. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28042. * @returns the GeometryBufferRenderer
  28043. */
  28044. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28045. if (ratio === void 0) { ratio = 1; }
  28046. if (this._geometryBufferRenderer) {
  28047. return this._geometryBufferRenderer;
  28048. }
  28049. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28050. if (!this._geometryBufferRenderer.isSupported) {
  28051. this._geometryBufferRenderer = null;
  28052. }
  28053. return this._geometryBufferRenderer;
  28054. };
  28055. /**
  28056. * Disables the GeometryBufferRender associated with the scene
  28057. */
  28058. Scene.prototype.disableGeometryBufferRenderer = function () {
  28059. if (!this._geometryBufferRenderer) {
  28060. return;
  28061. }
  28062. this._geometryBufferRenderer.dispose();
  28063. this._geometryBufferRenderer = null;
  28064. };
  28065. /**
  28066. * Freeze all materials
  28067. * A frozen material will not be updatable but should be faster to render
  28068. */
  28069. Scene.prototype.freezeMaterials = function () {
  28070. for (var i = 0; i < this.materials.length; i++) {
  28071. this.materials[i].freeze();
  28072. }
  28073. };
  28074. /**
  28075. * Unfreeze all materials
  28076. * A frozen material will not be updatable but should be faster to render
  28077. */
  28078. Scene.prototype.unfreezeMaterials = function () {
  28079. for (var i = 0; i < this.materials.length; i++) {
  28080. this.materials[i].unfreeze();
  28081. }
  28082. };
  28083. /**
  28084. * Releases all held ressources
  28085. */
  28086. Scene.prototype.dispose = function () {
  28087. this.beforeRender = null;
  28088. this.afterRender = null;
  28089. this.skeletons = [];
  28090. this.morphTargetManagers = [];
  28091. this.importedMeshesFiles = new Array();
  28092. this.stopAllAnimations();
  28093. this.resetCachedMaterial();
  28094. for (var key in this._depthRenderer) {
  28095. this._depthRenderer[key].dispose();
  28096. }
  28097. if (this._gamepadManager) {
  28098. this._gamepadManager.dispose();
  28099. this._gamepadManager = null;
  28100. }
  28101. // Smart arrays
  28102. if (this.activeCamera) {
  28103. this.activeCamera._activeMeshes.dispose();
  28104. this.activeCamera = null;
  28105. }
  28106. this._activeMeshes.dispose();
  28107. this._renderingManager.dispose();
  28108. this._processedMaterials.dispose();
  28109. this._activeParticleSystems.dispose();
  28110. this._activeSkeletons.dispose();
  28111. this._softwareSkinnedMeshes.dispose();
  28112. this._renderTargets.dispose();
  28113. this._registeredForLateAnimationBindings.dispose();
  28114. if (this._boundingBoxRenderer) {
  28115. this._boundingBoxRenderer.dispose();
  28116. }
  28117. this._meshesForIntersections.dispose();
  28118. this._toBeDisposed.dispose();
  28119. // Abort active requests
  28120. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28121. var request = _a[_i];
  28122. request.abort();
  28123. }
  28124. // Debug layer
  28125. if (this._debugLayer) {
  28126. this._debugLayer.hide();
  28127. }
  28128. // Events
  28129. this.onDisposeObservable.notifyObservers(this);
  28130. this.onDisposeObservable.clear();
  28131. this.onBeforeRenderObservable.clear();
  28132. this.onAfterRenderObservable.clear();
  28133. this.onBeforeRenderTargetsRenderObservable.clear();
  28134. this.onAfterRenderTargetsRenderObservable.clear();
  28135. this.onAfterStepObservable.clear();
  28136. this.onBeforeStepObservable.clear();
  28137. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28138. this.onAfterActiveMeshesEvaluationObservable.clear();
  28139. this.onBeforeParticlesRenderingObservable.clear();
  28140. this.onAfterParticlesRenderingObservable.clear();
  28141. this.onBeforeSpritesRenderingObservable.clear();
  28142. this.onAfterSpritesRenderingObservable.clear();
  28143. this.onBeforeDrawPhaseObservable.clear();
  28144. this.onAfterDrawPhaseObservable.clear();
  28145. this.onBeforePhysicsObservable.clear();
  28146. this.onAfterPhysicsObservable.clear();
  28147. this.onBeforeAnimationsObservable.clear();
  28148. this.onAfterAnimationsObservable.clear();
  28149. this.onDataLoadedObservable.clear();
  28150. this.detachControl();
  28151. // Release sounds & sounds tracks
  28152. if (BABYLON.AudioEngine) {
  28153. this.disposeSounds();
  28154. }
  28155. // VR Helper
  28156. if (this.VRHelper) {
  28157. this.VRHelper.dispose();
  28158. }
  28159. // Detach cameras
  28160. var canvas = this._engine.getRenderingCanvas();
  28161. if (canvas) {
  28162. var index;
  28163. for (index = 0; index < this.cameras.length; index++) {
  28164. this.cameras[index].detachControl(canvas);
  28165. }
  28166. }
  28167. // Release animation groups
  28168. while (this.animationGroups.length) {
  28169. this.animationGroups[0].dispose();
  28170. }
  28171. // Release lights
  28172. while (this.lights.length) {
  28173. this.lights[0].dispose();
  28174. }
  28175. // Release meshes
  28176. while (this.meshes.length) {
  28177. this.meshes[0].dispose(true);
  28178. }
  28179. while (this.transformNodes.length) {
  28180. this.removeTransformNode(this.transformNodes[0]);
  28181. }
  28182. // Release cameras
  28183. while (this.cameras.length) {
  28184. this.cameras[0].dispose();
  28185. }
  28186. // Release materials
  28187. if (this.defaultMaterial) {
  28188. this.defaultMaterial.dispose();
  28189. }
  28190. while (this.multiMaterials.length) {
  28191. this.multiMaterials[0].dispose();
  28192. }
  28193. while (this.materials.length) {
  28194. this.materials[0].dispose();
  28195. }
  28196. // Release particles
  28197. while (this.particleSystems.length) {
  28198. this.particleSystems[0].dispose();
  28199. }
  28200. // Release sprites
  28201. while (this.spriteManagers.length) {
  28202. this.spriteManagers[0].dispose();
  28203. }
  28204. // Release postProcesses
  28205. while (this.postProcesses.length) {
  28206. this.postProcesses[0].dispose();
  28207. }
  28208. // Release layers
  28209. while (this.layers.length) {
  28210. this.layers[0].dispose();
  28211. }
  28212. while (this.effectLayers.length) {
  28213. this.effectLayers[0].dispose();
  28214. }
  28215. // Release textures
  28216. while (this.textures.length) {
  28217. this.textures[0].dispose();
  28218. }
  28219. // Release UBO
  28220. this._sceneUbo.dispose();
  28221. if (this._alternateSceneUbo) {
  28222. this._alternateSceneUbo.dispose();
  28223. }
  28224. // Post-processes
  28225. this.postProcessManager.dispose();
  28226. if (this._postProcessRenderPipelineManager) {
  28227. this._postProcessRenderPipelineManager.dispose();
  28228. }
  28229. // Physics
  28230. if (this._physicsEngine) {
  28231. this.disablePhysicsEngine();
  28232. }
  28233. // Remove from engine
  28234. index = this._engine.scenes.indexOf(this);
  28235. if (index > -1) {
  28236. this._engine.scenes.splice(index, 1);
  28237. }
  28238. this._engine.wipeCaches(true);
  28239. this._isDisposed = true;
  28240. };
  28241. Object.defineProperty(Scene.prototype, "isDisposed", {
  28242. /**
  28243. * Gets if the scene is already disposed
  28244. */
  28245. get: function () {
  28246. return this._isDisposed;
  28247. },
  28248. enumerable: true,
  28249. configurable: true
  28250. });
  28251. /**
  28252. * Releases sounds & soundtracks
  28253. */
  28254. Scene.prototype.disposeSounds = function () {
  28255. if (!this._mainSoundTrack) {
  28256. return;
  28257. }
  28258. this.mainSoundTrack.dispose();
  28259. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28260. this.soundTracks[scIndex].dispose();
  28261. }
  28262. };
  28263. /**
  28264. * Call this function to reduce memory footprint of the scene.
  28265. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28266. */
  28267. Scene.prototype.clearCachedVertexData = function () {
  28268. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28269. var mesh = this.meshes[meshIndex];
  28270. var geometry = mesh.geometry;
  28271. if (geometry) {
  28272. geometry._indices = [];
  28273. for (var vbName in geometry._vertexBuffers) {
  28274. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28275. continue;
  28276. }
  28277. geometry._vertexBuffers[vbName]._buffer._data = null;
  28278. }
  28279. }
  28280. }
  28281. };
  28282. /**
  28283. * This function will remove the local cached buffer data from texture.
  28284. * It will save memory but will prevent the texture from being rebuilt
  28285. */
  28286. Scene.prototype.cleanCachedTextureBuffer = function () {
  28287. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28288. var baseTexture = _a[_i];
  28289. var buffer = baseTexture._buffer;
  28290. if (buffer) {
  28291. baseTexture._buffer = null;
  28292. }
  28293. }
  28294. };
  28295. // Octrees
  28296. /**
  28297. * Get the world extend vectors with an optional filter
  28298. *
  28299. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28300. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28301. */
  28302. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28303. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28304. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28305. filterPredicate = filterPredicate || (function () { return true; });
  28306. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28307. mesh.computeWorldMatrix(true);
  28308. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28309. return;
  28310. }
  28311. var boundingInfo = mesh.getBoundingInfo();
  28312. var minBox = boundingInfo.boundingBox.minimumWorld;
  28313. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28314. BABYLON.Tools.CheckExtends(minBox, min, max);
  28315. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28316. });
  28317. return {
  28318. min: min,
  28319. max: max
  28320. };
  28321. };
  28322. /**
  28323. * Creates or updates the octree used to boost selection (picking)
  28324. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28325. * @param maxCapacity defines the maximum capacity per leaf
  28326. * @param maxDepth defines the maximum depth of the octree
  28327. * @returns an octree of AbstractMesh
  28328. */
  28329. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28330. if (maxCapacity === void 0) { maxCapacity = 64; }
  28331. if (maxDepth === void 0) { maxDepth = 2; }
  28332. if (!this._selectionOctree) {
  28333. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28334. }
  28335. var worldExtends = this.getWorldExtends();
  28336. // Update octree
  28337. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28338. return this._selectionOctree;
  28339. };
  28340. // Picking
  28341. /**
  28342. * Creates a ray that can be used to pick in the scene
  28343. * @param x defines the x coordinate of the origin (on-screen)
  28344. * @param y defines the y coordinate of the origin (on-screen)
  28345. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28346. * @param camera defines the camera to use for the picking
  28347. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28348. * @returns a Ray
  28349. */
  28350. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28351. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28352. var result = BABYLON.Ray.Zero();
  28353. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28354. return result;
  28355. };
  28356. /**
  28357. * Creates a ray that can be used to pick in the scene
  28358. * @param x defines the x coordinate of the origin (on-screen)
  28359. * @param y defines the y coordinate of the origin (on-screen)
  28360. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28361. * @param result defines the ray where to store the picking ray
  28362. * @param camera defines the camera to use for the picking
  28363. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28364. * @returns the current scene
  28365. */
  28366. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28367. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28368. var engine = this._engine;
  28369. if (!camera) {
  28370. if (!this.activeCamera)
  28371. throw new Error("Active camera not set");
  28372. camera = this.activeCamera;
  28373. }
  28374. var cameraViewport = camera.viewport;
  28375. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28376. // Moving coordinates to local viewport world
  28377. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28378. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28379. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28380. return this;
  28381. };
  28382. /**
  28383. * Creates a ray that can be used to pick in the scene
  28384. * @param x defines the x coordinate of the origin (on-screen)
  28385. * @param y defines the y coordinate of the origin (on-screen)
  28386. * @param camera defines the camera to use for the picking
  28387. * @returns a Ray
  28388. */
  28389. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28390. var result = BABYLON.Ray.Zero();
  28391. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28392. return result;
  28393. };
  28394. /**
  28395. * Creates a ray that can be used to pick in the scene
  28396. * @param x defines the x coordinate of the origin (on-screen)
  28397. * @param y defines the y coordinate of the origin (on-screen)
  28398. * @param result defines the ray where to store the picking ray
  28399. * @param camera defines the camera to use for the picking
  28400. * @returns the current scene
  28401. */
  28402. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28403. if (!BABYLON.PickingInfo) {
  28404. return this;
  28405. }
  28406. var engine = this._engine;
  28407. if (!camera) {
  28408. if (!this.activeCamera)
  28409. throw new Error("Active camera not set");
  28410. camera = this.activeCamera;
  28411. }
  28412. var cameraViewport = camera.viewport;
  28413. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28414. var identity = BABYLON.Matrix.Identity();
  28415. // Moving coordinates to local viewport world
  28416. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28417. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28418. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28419. return this;
  28420. };
  28421. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28422. if (!BABYLON.PickingInfo) {
  28423. return null;
  28424. }
  28425. var pickingInfo = null;
  28426. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28427. var mesh = this.meshes[meshIndex];
  28428. if (predicate) {
  28429. if (!predicate(mesh)) {
  28430. continue;
  28431. }
  28432. }
  28433. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28434. continue;
  28435. }
  28436. var world = mesh.getWorldMatrix();
  28437. var ray = rayFunction(world);
  28438. var result = mesh.intersects(ray, fastCheck);
  28439. if (!result || !result.hit)
  28440. continue;
  28441. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28442. continue;
  28443. pickingInfo = result;
  28444. if (fastCheck) {
  28445. break;
  28446. }
  28447. }
  28448. return pickingInfo || new BABYLON.PickingInfo();
  28449. };
  28450. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28451. if (!BABYLON.PickingInfo) {
  28452. return null;
  28453. }
  28454. var pickingInfos = new Array();
  28455. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28456. var mesh = this.meshes[meshIndex];
  28457. if (predicate) {
  28458. if (!predicate(mesh)) {
  28459. continue;
  28460. }
  28461. }
  28462. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28463. continue;
  28464. }
  28465. var world = mesh.getWorldMatrix();
  28466. var ray = rayFunction(world);
  28467. var result = mesh.intersects(ray, false);
  28468. if (!result || !result.hit)
  28469. continue;
  28470. pickingInfos.push(result);
  28471. }
  28472. return pickingInfos;
  28473. };
  28474. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28475. if (!BABYLON.PickingInfo) {
  28476. return null;
  28477. }
  28478. var pickingInfo = null;
  28479. if (!camera) {
  28480. if (!this.activeCamera) {
  28481. return null;
  28482. }
  28483. camera = this.activeCamera;
  28484. }
  28485. if (this.spriteManagers.length > 0) {
  28486. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28487. var spriteManager = this.spriteManagers[spriteIndex];
  28488. if (!spriteManager.isPickable) {
  28489. continue;
  28490. }
  28491. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28492. if (!result || !result.hit)
  28493. continue;
  28494. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28495. continue;
  28496. pickingInfo = result;
  28497. if (fastCheck) {
  28498. break;
  28499. }
  28500. }
  28501. }
  28502. return pickingInfo || new BABYLON.PickingInfo();
  28503. };
  28504. /** Launch a ray to try to pick a mesh in the scene
  28505. * @param x position on screen
  28506. * @param y position on screen
  28507. * @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
  28508. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28509. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28510. * @returns a PickingInfo
  28511. */
  28512. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28513. var _this = this;
  28514. if (!BABYLON.PickingInfo) {
  28515. return null;
  28516. }
  28517. return this._internalPick(function (world) {
  28518. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28519. return _this._tempPickingRay;
  28520. }, predicate, fastCheck);
  28521. };
  28522. /** Launch a ray to try to pick a sprite in the scene
  28523. * @param x position on screen
  28524. * @param y position on screen
  28525. * @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
  28526. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28527. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28528. * @returns a PickingInfo
  28529. */
  28530. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28531. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28532. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28533. };
  28534. /** Use the given ray to pick a mesh in the scene
  28535. * @param ray The ray to use to pick meshes
  28536. * @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
  28537. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28538. * @returns a PickingInfo
  28539. */
  28540. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28541. var _this = this;
  28542. var result = this._internalPick(function (world) {
  28543. if (!_this._pickWithRayInverseMatrix) {
  28544. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28545. }
  28546. world.invertToRef(_this._pickWithRayInverseMatrix);
  28547. if (!_this._cachedRayForTransform) {
  28548. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28549. }
  28550. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28551. return _this._cachedRayForTransform;
  28552. }, predicate, fastCheck);
  28553. if (result) {
  28554. result.ray = ray;
  28555. }
  28556. return result;
  28557. };
  28558. /**
  28559. * Launch a ray to try to pick a mesh in the scene
  28560. * @param x X position on screen
  28561. * @param y Y position on screen
  28562. * @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
  28563. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28564. * @returns an array of PickingInfo
  28565. */
  28566. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28567. var _this = this;
  28568. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28569. };
  28570. /**
  28571. * Launch a ray to try to pick a mesh in the scene
  28572. * @param ray Ray to use
  28573. * @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
  28574. * @returns an array of PickingInfo
  28575. */
  28576. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28577. var _this = this;
  28578. return this._internalMultiPick(function (world) {
  28579. if (!_this._pickWithRayInverseMatrix) {
  28580. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28581. }
  28582. world.invertToRef(_this._pickWithRayInverseMatrix);
  28583. if (!_this._cachedRayForTransform) {
  28584. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28585. }
  28586. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28587. return _this._cachedRayForTransform;
  28588. }, predicate);
  28589. };
  28590. /**
  28591. * Force the value of meshUnderPointer
  28592. * @param mesh defines the mesh to use
  28593. */
  28594. Scene.prototype.setPointerOverMesh = function (mesh) {
  28595. if (this._pointerOverMesh === mesh) {
  28596. return;
  28597. }
  28598. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28599. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28600. }
  28601. this._pointerOverMesh = mesh;
  28602. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28603. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28604. }
  28605. };
  28606. /**
  28607. * Gets the mesh under the pointer
  28608. * @returns a Mesh or null if no mesh is under the pointer
  28609. */
  28610. Scene.prototype.getPointerOverMesh = function () {
  28611. return this._pointerOverMesh;
  28612. };
  28613. /**
  28614. * Force the sprite under the pointer
  28615. * @param sprite defines the sprite to use
  28616. */
  28617. Scene.prototype.setPointerOverSprite = function (sprite) {
  28618. if (this._pointerOverSprite === sprite) {
  28619. return;
  28620. }
  28621. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28622. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28623. }
  28624. this._pointerOverSprite = sprite;
  28625. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28626. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28627. }
  28628. };
  28629. /**
  28630. * Gets the sprite under the pointer
  28631. * @returns a Sprite or null if no sprite is under the pointer
  28632. */
  28633. Scene.prototype.getPointerOverSprite = function () {
  28634. return this._pointerOverSprite;
  28635. };
  28636. // Physics
  28637. /**
  28638. * Gets the current physics engine
  28639. * @returns a PhysicsEngine or null if none attached
  28640. */
  28641. Scene.prototype.getPhysicsEngine = function () {
  28642. return this._physicsEngine;
  28643. };
  28644. /**
  28645. * Enables physics to the current scene
  28646. * @param gravity defines the scene's gravity for the physics engine
  28647. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28648. * @return a boolean indicating if the physics engine was initialized
  28649. */
  28650. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28651. if (gravity === void 0) { gravity = null; }
  28652. if (this._physicsEngine) {
  28653. return true;
  28654. }
  28655. try {
  28656. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28657. return true;
  28658. }
  28659. catch (e) {
  28660. BABYLON.Tools.Error(e.message);
  28661. return false;
  28662. }
  28663. };
  28664. /**
  28665. * Disables and disposes the physics engine associated with the scene
  28666. */
  28667. Scene.prototype.disablePhysicsEngine = function () {
  28668. if (!this._physicsEngine) {
  28669. return;
  28670. }
  28671. this._physicsEngine.dispose();
  28672. this._physicsEngine = null;
  28673. };
  28674. /**
  28675. * Gets a boolean indicating if there is an active physics engine
  28676. * @returns a boolean indicating if there is an active physics engine
  28677. */
  28678. Scene.prototype.isPhysicsEnabled = function () {
  28679. return this._physicsEngine !== undefined;
  28680. };
  28681. /**
  28682. * Deletes a physics compound impostor
  28683. * @param compound defines the compound to delete
  28684. */
  28685. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28686. var mesh = compound.parts[0].mesh;
  28687. if (mesh.physicsImpostor) {
  28688. mesh.physicsImpostor.dispose( /*true*/);
  28689. mesh.physicsImpostor = null;
  28690. }
  28691. };
  28692. // Misc.
  28693. /** @hidden */
  28694. Scene.prototype._rebuildGeometries = function () {
  28695. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28696. var geometry = _a[_i];
  28697. geometry._rebuild();
  28698. }
  28699. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28700. var mesh = _c[_b];
  28701. mesh._rebuild();
  28702. }
  28703. if (this.postProcessManager) {
  28704. this.postProcessManager._rebuild();
  28705. }
  28706. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28707. var layer = _e[_d];
  28708. layer._rebuild();
  28709. }
  28710. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28711. var effectLayer = _g[_f];
  28712. effectLayer._rebuild();
  28713. }
  28714. if (this._boundingBoxRenderer) {
  28715. this._boundingBoxRenderer._rebuild();
  28716. }
  28717. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28718. var system = _j[_h];
  28719. system.rebuild();
  28720. }
  28721. if (this._postProcessRenderPipelineManager) {
  28722. this._postProcessRenderPipelineManager._rebuild();
  28723. }
  28724. };
  28725. /** @hidden */
  28726. Scene.prototype._rebuildTextures = function () {
  28727. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28728. var texture = _a[_i];
  28729. texture._rebuild();
  28730. }
  28731. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28732. };
  28733. /**
  28734. * Creates a default light for the scene.
  28735. * @param replace Whether to replace the existing lights in the scene.
  28736. */
  28737. Scene.prototype.createDefaultLight = function (replace) {
  28738. if (replace === void 0) { replace = false; }
  28739. // Dispose existing light in replace mode.
  28740. if (replace) {
  28741. if (this.lights) {
  28742. for (var i = 0; i < this.lights.length; i++) {
  28743. this.lights[i].dispose();
  28744. }
  28745. }
  28746. }
  28747. // Light
  28748. if (this.lights.length === 0) {
  28749. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28750. }
  28751. };
  28752. /**
  28753. * Creates a default camera for the scene.
  28754. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28755. * @param replace Whether to replace the existing active camera in the scene.
  28756. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28757. */
  28758. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28759. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28760. if (replace === void 0) { replace = false; }
  28761. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28762. // Dispose existing camera in replace mode.
  28763. if (replace) {
  28764. if (this.activeCamera) {
  28765. this.activeCamera.dispose();
  28766. this.activeCamera = null;
  28767. }
  28768. }
  28769. // Camera
  28770. if (!this.activeCamera) {
  28771. var worldExtends = this.getWorldExtends();
  28772. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28773. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28774. var camera;
  28775. var radius = worldSize.length() * 1.5;
  28776. // empty scene scenario!
  28777. if (!isFinite(radius)) {
  28778. radius = 1;
  28779. worldCenter.copyFromFloats(0, 0, 0);
  28780. }
  28781. if (createArcRotateCamera) {
  28782. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28783. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28784. arcRotateCamera.wheelPrecision = 100 / radius;
  28785. camera = arcRotateCamera;
  28786. }
  28787. else {
  28788. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28789. freeCamera.setTarget(worldCenter);
  28790. camera = freeCamera;
  28791. }
  28792. camera.minZ = radius * 0.01;
  28793. camera.maxZ = radius * 1000;
  28794. camera.speed = radius * 0.2;
  28795. this.activeCamera = camera;
  28796. var canvas = this.getEngine().getRenderingCanvas();
  28797. if (attachCameraControls && canvas) {
  28798. camera.attachControl(canvas);
  28799. }
  28800. }
  28801. };
  28802. /**
  28803. * Creates a default camera and a default light
  28804. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28805. * @param replace defines if the camera and/or light will replace the existing ones
  28806. * @param attachCameraControls defines if attachControl will be called on the new camera
  28807. */
  28808. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28809. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28810. if (replace === void 0) { replace = false; }
  28811. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28812. this.createDefaultLight(replace);
  28813. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28814. };
  28815. /**
  28816. * Creates a new sky box
  28817. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28818. * @param environmentTexture defines the texture to use as environment texture
  28819. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28820. * @param scale defines the overall scale of the skybox
  28821. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28822. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28823. * @returns a new mesh holding the sky box
  28824. */
  28825. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28826. if (pbr === void 0) { pbr = false; }
  28827. if (scale === void 0) { scale = 1000; }
  28828. if (blur === void 0) { blur = 0; }
  28829. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28830. if (!environmentTexture) {
  28831. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28832. return null;
  28833. }
  28834. if (setGlobalEnvTexture) {
  28835. if (environmentTexture) {
  28836. this.environmentTexture = environmentTexture;
  28837. }
  28838. }
  28839. // Skybox
  28840. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28841. if (pbr) {
  28842. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28843. hdrSkyboxMaterial.backFaceCulling = false;
  28844. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28845. if (hdrSkyboxMaterial.reflectionTexture) {
  28846. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28847. }
  28848. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28849. hdrSkyboxMaterial.disableLighting = true;
  28850. hdrSkyboxMaterial.twoSidedLighting = true;
  28851. hdrSkybox.infiniteDistance = true;
  28852. hdrSkybox.material = hdrSkyboxMaterial;
  28853. }
  28854. else {
  28855. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28856. skyboxMaterial.backFaceCulling = false;
  28857. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28858. if (skyboxMaterial.reflectionTexture) {
  28859. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28860. }
  28861. skyboxMaterial.disableLighting = true;
  28862. hdrSkybox.infiniteDistance = true;
  28863. hdrSkybox.material = skyboxMaterial;
  28864. }
  28865. return hdrSkybox;
  28866. };
  28867. /**
  28868. * Creates a new environment
  28869. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28870. * @param options defines the options you can use to configure the environment
  28871. * @returns the new EnvironmentHelper
  28872. */
  28873. Scene.prototype.createDefaultEnvironment = function (options) {
  28874. if (BABYLON.EnvironmentHelper) {
  28875. return new BABYLON.EnvironmentHelper(options, this);
  28876. }
  28877. return null;
  28878. };
  28879. /**
  28880. * Creates a new VREXperienceHelper
  28881. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28882. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28883. * @returns a new VREXperienceHelper
  28884. */
  28885. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28886. if (webVROptions === void 0) { webVROptions = {}; }
  28887. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28888. };
  28889. // Tags
  28890. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28891. if (tagsQuery === undefined) {
  28892. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28893. return list;
  28894. }
  28895. var listByTags = [];
  28896. forEach = forEach || (function (item) { return; });
  28897. for (var i in list) {
  28898. var item = list[i];
  28899. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28900. listByTags.push(item);
  28901. forEach(item);
  28902. }
  28903. }
  28904. return listByTags;
  28905. };
  28906. /**
  28907. * Get a list of meshes by tags
  28908. * @param tagsQuery defines the tags query to use
  28909. * @param forEach defines a predicate used to filter results
  28910. * @returns an array of Mesh
  28911. */
  28912. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28913. return this._getByTags(this.meshes, tagsQuery, forEach);
  28914. };
  28915. /**
  28916. * Get a list of cameras by tags
  28917. * @param tagsQuery defines the tags query to use
  28918. * @param forEach defines a predicate used to filter results
  28919. * @returns an array of Camera
  28920. */
  28921. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28922. return this._getByTags(this.cameras, tagsQuery, forEach);
  28923. };
  28924. /**
  28925. * Get a list of lights by tags
  28926. * @param tagsQuery defines the tags query to use
  28927. * @param forEach defines a predicate used to filter results
  28928. * @returns an array of Light
  28929. */
  28930. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28931. return this._getByTags(this.lights, tagsQuery, forEach);
  28932. };
  28933. /**
  28934. * Get a list of materials by tags
  28935. * @param tagsQuery defines the tags query to use
  28936. * @param forEach defines a predicate used to filter results
  28937. * @returns an array of Material
  28938. */
  28939. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28940. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28941. };
  28942. /**
  28943. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28944. * This allowed control for front to back rendering or reversly depending of the special needs.
  28945. *
  28946. * @param renderingGroupId The rendering group id corresponding to its index
  28947. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28948. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28949. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28950. */
  28951. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28952. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28953. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28954. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28955. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28956. };
  28957. /**
  28958. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28959. *
  28960. * @param renderingGroupId The rendering group id corresponding to its index
  28961. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28962. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28963. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28964. */
  28965. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28966. if (depth === void 0) { depth = true; }
  28967. if (stencil === void 0) { stencil = true; }
  28968. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28969. };
  28970. /**
  28971. * Will flag all materials as dirty to trigger new shader compilation
  28972. * @param flag defines the flag used to specify which material part must be marked as dirty
  28973. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28974. */
  28975. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28976. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28977. var material = _a[_i];
  28978. if (predicate && !predicate(material)) {
  28979. continue;
  28980. }
  28981. material.markAsDirty(flag);
  28982. }
  28983. };
  28984. /** @hidden */
  28985. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28986. var _this = this;
  28987. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28988. this._activeRequests.push(request);
  28989. request.onCompleteObservable.add(function (request) {
  28990. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28991. });
  28992. return request;
  28993. };
  28994. /** @hidden */
  28995. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28996. var _this = this;
  28997. return new Promise(function (resolve, reject) {
  28998. _this._loadFile(url, function (data) {
  28999. resolve(data);
  29000. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29001. reject(exception);
  29002. });
  29003. });
  29004. };
  29005. // Statics
  29006. Scene._FOGMODE_NONE = 0;
  29007. Scene._FOGMODE_EXP = 1;
  29008. Scene._FOGMODE_EXP2 = 2;
  29009. Scene._FOGMODE_LINEAR = 3;
  29010. Scene._uniqueIdCounter = 0;
  29011. /**
  29012. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29013. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29014. */
  29015. Scene.MinDeltaTime = 1.0;
  29016. /**
  29017. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29018. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29019. */
  29020. Scene.MaxDeltaTime = 1000.0;
  29021. /** The distance in pixel that you have to move to prevent some events */
  29022. Scene.DragMovementThreshold = 10; // in pixels
  29023. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29024. Scene.LongPressDelay = 500; // in milliseconds
  29025. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29026. Scene.DoubleClickDelay = 300; // in milliseconds
  29027. /** If you need to check double click without raising a single click at first click, enable this flag */
  29028. Scene.ExclusiveDoubleClickMode = false;
  29029. return Scene;
  29030. }());
  29031. BABYLON.Scene = Scene;
  29032. })(BABYLON || (BABYLON = {}));
  29033. //# sourceMappingURL=babylon.scene.js.map
  29034. var BABYLON;
  29035. (function (BABYLON) {
  29036. /**
  29037. * Set of assets to keep when moving a scene into an asset container.
  29038. */
  29039. var KeepAssets = /** @class */ (function () {
  29040. function KeepAssets() {
  29041. /**
  29042. * Cameras to keep.
  29043. */
  29044. this.cameras = new Array();
  29045. /**
  29046. * Lights to keep.
  29047. */
  29048. this.lights = new Array();
  29049. /**
  29050. * Meshes to keep.
  29051. */
  29052. this.meshes = new Array();
  29053. /**
  29054. * Skeletons to keep.
  29055. */
  29056. this.skeletons = new Array();
  29057. /**
  29058. * ParticleSystems to keep.
  29059. */
  29060. this.particleSystems = new Array();
  29061. /**
  29062. * Animations to keep.
  29063. */
  29064. this.animations = new Array();
  29065. /**
  29066. * AnimationGroups to keep.
  29067. */
  29068. this.animationGroups = new Array();
  29069. /**
  29070. * MultiMaterials to keep.
  29071. */
  29072. this.multiMaterials = new Array();
  29073. /**
  29074. * Materials to keep.
  29075. */
  29076. this.materials = new Array();
  29077. /**
  29078. * MorphTargetManagers to keep.
  29079. */
  29080. this.morphTargetManagers = new Array();
  29081. /**
  29082. * Geometries to keep.
  29083. */
  29084. this.geometries = new Array();
  29085. /**
  29086. * TransformNodes to keep.
  29087. */
  29088. this.transformNodes = new Array();
  29089. /**
  29090. * LensFlareSystems to keep.
  29091. */
  29092. this.lensFlareSystems = new Array();
  29093. /**
  29094. * ShadowGenerators to keep.
  29095. */
  29096. this.shadowGenerators = new Array();
  29097. /**
  29098. * ActionManagers to keep.
  29099. */
  29100. this.actionManagers = new Array();
  29101. /**
  29102. * Sounds to keep.
  29103. */
  29104. this.sounds = new Array();
  29105. /**
  29106. * Textures to keep.
  29107. */
  29108. this.textures = new Array();
  29109. /**
  29110. * Effect layers to keep.
  29111. */
  29112. this.effectLayers = new Array();
  29113. }
  29114. return KeepAssets;
  29115. }());
  29116. BABYLON.KeepAssets = KeepAssets;
  29117. /**
  29118. * Container with a set of assets that can be added or removed from a scene.
  29119. */
  29120. var AssetContainer = /** @class */ (function () {
  29121. /**
  29122. * Instantiates an AssetContainer.
  29123. * @param scene The scene the AssetContainer belongs to.
  29124. */
  29125. function AssetContainer(scene) {
  29126. // Objects
  29127. /**
  29128. * Cameras populated in the container.
  29129. */
  29130. this.cameras = new Array();
  29131. /**
  29132. * Lights populated in the container.
  29133. */
  29134. this.lights = new Array();
  29135. /**
  29136. * Meshes populated in the container.
  29137. */
  29138. this.meshes = new Array();
  29139. /**
  29140. * Skeletons populated in the container.
  29141. */
  29142. this.skeletons = new Array();
  29143. /**
  29144. * ParticleSystems populated in the container.
  29145. */
  29146. this.particleSystems = new Array();
  29147. /**
  29148. * Animations populated in the container.
  29149. */
  29150. this.animations = new Array();
  29151. /**
  29152. * AnimationGroups populated in the container.
  29153. */
  29154. this.animationGroups = new Array();
  29155. /**
  29156. * MultiMaterials populated in the container.
  29157. */
  29158. this.multiMaterials = new Array();
  29159. /**
  29160. * Materials populated in the container.
  29161. */
  29162. this.materials = new Array();
  29163. /**
  29164. * MorphTargetManagers populated in the container.
  29165. */
  29166. this.morphTargetManagers = new Array();
  29167. /**
  29168. * Geometries populated in the container.
  29169. */
  29170. this.geometries = new Array();
  29171. /**
  29172. * TransformNodes populated in the container.
  29173. */
  29174. this.transformNodes = new Array();
  29175. /**
  29176. * LensFlareSystems populated in the container.
  29177. */
  29178. this.lensFlareSystems = new Array();
  29179. /**
  29180. * ShadowGenerators populated in the container.
  29181. */
  29182. this.shadowGenerators = new Array();
  29183. /**
  29184. * ActionManagers populated in the container.
  29185. */
  29186. this.actionManagers = new Array();
  29187. /**
  29188. * Sounds populated in the container.
  29189. */
  29190. this.sounds = new Array();
  29191. /**
  29192. * Textures populated in the container.
  29193. */
  29194. this.textures = new Array();
  29195. /**
  29196. * Effect layers populated in the container.
  29197. */
  29198. this.effectLayers = new Array();
  29199. this.scene = scene;
  29200. }
  29201. /**
  29202. * Adds all the assets from the container to the scene.
  29203. */
  29204. AssetContainer.prototype.addAllToScene = function () {
  29205. var _this = this;
  29206. this.cameras.forEach(function (o) {
  29207. _this.scene.addCamera(o);
  29208. });
  29209. this.lights.forEach(function (o) {
  29210. _this.scene.addLight(o);
  29211. });
  29212. this.meshes.forEach(function (o) {
  29213. _this.scene.addMesh(o);
  29214. });
  29215. this.skeletons.forEach(function (o) {
  29216. _this.scene.addSkeleton(o);
  29217. });
  29218. this.particleSystems.forEach(function (o) {
  29219. _this.scene.addParticleSystem(o);
  29220. });
  29221. this.animations.forEach(function (o) {
  29222. _this.scene.addAnimation(o);
  29223. });
  29224. this.animationGroups.forEach(function (o) {
  29225. _this.scene.addAnimationGroup(o);
  29226. });
  29227. this.multiMaterials.forEach(function (o) {
  29228. _this.scene.addMultiMaterial(o);
  29229. });
  29230. this.materials.forEach(function (o) {
  29231. _this.scene.addMaterial(o);
  29232. });
  29233. this.morphTargetManagers.forEach(function (o) {
  29234. _this.scene.addMorphTargetManager(o);
  29235. });
  29236. this.geometries.forEach(function (o) {
  29237. _this.scene.addGeometry(o);
  29238. });
  29239. this.transformNodes.forEach(function (o) {
  29240. _this.scene.addTransformNode(o);
  29241. });
  29242. this.lensFlareSystems.forEach(function (o) {
  29243. _this.scene.addLensFlareSystem(o);
  29244. });
  29245. this.actionManagers.forEach(function (o) {
  29246. _this.scene.addActionManager(o);
  29247. });
  29248. this.sounds.forEach(function (o) {
  29249. o.play();
  29250. o.autoplay = true;
  29251. _this.scene.mainSoundTrack.AddSound(o);
  29252. });
  29253. this.textures.forEach(function (o) {
  29254. _this.scene.addTexture(o);
  29255. });
  29256. this.effectLayers.forEach(function (o) {
  29257. _this.scene.addEffectLayer(o);
  29258. });
  29259. };
  29260. /**
  29261. * Removes all the assets in the container from the scene
  29262. */
  29263. AssetContainer.prototype.removeAllFromScene = function () {
  29264. var _this = this;
  29265. this.cameras.forEach(function (o) {
  29266. _this.scene.removeCamera(o);
  29267. });
  29268. this.lights.forEach(function (o) {
  29269. _this.scene.removeLight(o);
  29270. });
  29271. this.meshes.forEach(function (o) {
  29272. _this.scene.removeMesh(o);
  29273. });
  29274. this.skeletons.forEach(function (o) {
  29275. _this.scene.removeSkeleton(o);
  29276. });
  29277. this.particleSystems.forEach(function (o) {
  29278. _this.scene.removeParticleSystem(o);
  29279. });
  29280. this.animations.forEach(function (o) {
  29281. _this.scene.removeAnimation(o);
  29282. });
  29283. this.animationGroups.forEach(function (o) {
  29284. _this.scene.removeAnimationGroup(o);
  29285. });
  29286. this.multiMaterials.forEach(function (o) {
  29287. _this.scene.removeMultiMaterial(o);
  29288. });
  29289. this.materials.forEach(function (o) {
  29290. _this.scene.removeMaterial(o);
  29291. });
  29292. this.morphTargetManagers.forEach(function (o) {
  29293. _this.scene.removeMorphTargetManager(o);
  29294. });
  29295. this.geometries.forEach(function (o) {
  29296. _this.scene.removeGeometry(o);
  29297. });
  29298. this.transformNodes.forEach(function (o) {
  29299. _this.scene.removeTransformNode(o);
  29300. });
  29301. this.lensFlareSystems.forEach(function (o) {
  29302. _this.scene.removeLensFlareSystem(o);
  29303. });
  29304. this.actionManagers.forEach(function (o) {
  29305. _this.scene.removeActionManager(o);
  29306. });
  29307. this.sounds.forEach(function (o) {
  29308. o.stop();
  29309. o.autoplay = false;
  29310. _this.scene.mainSoundTrack.RemoveSound(o);
  29311. });
  29312. this.textures.forEach(function (o) {
  29313. _this.scene.removeTexture(o);
  29314. });
  29315. this.effectLayers.forEach(function (o) {
  29316. _this.scene.removeEffectLayer(o);
  29317. });
  29318. };
  29319. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29320. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29321. var asset = sourceAssets_1[_i];
  29322. var move = true;
  29323. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29324. var keepAsset = keepAssets_1[_a];
  29325. if (asset === keepAsset) {
  29326. move = false;
  29327. break;
  29328. }
  29329. }
  29330. if (move) {
  29331. targetAssets.push(asset);
  29332. }
  29333. }
  29334. };
  29335. /**
  29336. * Removes all the assets contained in the scene and adds them to the container.
  29337. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29338. */
  29339. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29340. if (keepAssets === undefined) {
  29341. keepAssets = new KeepAssets();
  29342. }
  29343. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29344. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29345. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29346. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29347. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29348. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29349. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29350. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29351. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29352. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29353. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29354. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29355. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29356. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29357. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29358. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29359. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29360. this.removeAllFromScene();
  29361. };
  29362. /**
  29363. * 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.
  29364. * @returns the root mesh
  29365. */
  29366. AssetContainer.prototype.createRootMesh = function () {
  29367. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29368. this.meshes.forEach(function (m) {
  29369. if (!m.parent) {
  29370. rootMesh.addChild(m);
  29371. }
  29372. });
  29373. this.meshes.unshift(rootMesh);
  29374. return rootMesh;
  29375. };
  29376. return AssetContainer;
  29377. }());
  29378. BABYLON.AssetContainer = AssetContainer;
  29379. })(BABYLON || (BABYLON = {}));
  29380. //# sourceMappingURL=babylon.assetContainer.js.map
  29381. var BABYLON;
  29382. (function (BABYLON) {
  29383. var Buffer = /** @class */ (function () {
  29384. /**
  29385. * Constructor
  29386. * @param engine the engine
  29387. * @param data the data to use for this buffer
  29388. * @param updatable whether the data is updatable
  29389. * @param stride the stride (optional)
  29390. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29391. * @param instanced whether the buffer is instanced (optional)
  29392. * @param useBytes set to true if the stride in in bytes (optional)
  29393. */
  29394. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29395. if (stride === void 0) { stride = 0; }
  29396. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29397. if (instanced === void 0) { instanced = false; }
  29398. if (useBytes === void 0) { useBytes = false; }
  29399. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29400. this._engine = engine.getScene().getEngine();
  29401. }
  29402. else {
  29403. this._engine = engine;
  29404. }
  29405. this._updatable = updatable;
  29406. this._instanced = instanced;
  29407. this._data = data;
  29408. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29409. if (!postponeInternalCreation) { // by default
  29410. this.create();
  29411. }
  29412. }
  29413. /**
  29414. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29415. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29416. * @param offset defines offset in the buffer (0 by default)
  29417. * @param size defines the size in floats of attributes (position is 3 for instance)
  29418. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29419. * @param instanced defines if the vertex buffer contains indexed data
  29420. * @param useBytes defines if the offset and stride are in bytes
  29421. * @returns the new vertex buffer
  29422. */
  29423. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29424. if (useBytes === void 0) { useBytes = false; }
  29425. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29426. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29427. // a lot of these parameters are ignored as they are overriden by the buffer
  29428. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29429. };
  29430. // Properties
  29431. Buffer.prototype.isUpdatable = function () {
  29432. return this._updatable;
  29433. };
  29434. Buffer.prototype.getData = function () {
  29435. return this._data;
  29436. };
  29437. Buffer.prototype.getBuffer = function () {
  29438. return this._buffer;
  29439. };
  29440. /**
  29441. * Gets the stride in float32 units (i.e. byte stride / 4).
  29442. * May not be an integer if the byte stride is not divisible by 4.
  29443. * DEPRECATED. Use byteStride instead.
  29444. * @returns the stride in float32 units
  29445. */
  29446. Buffer.prototype.getStrideSize = function () {
  29447. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29448. };
  29449. // Methods
  29450. Buffer.prototype.create = function (data) {
  29451. if (data === void 0) { data = null; }
  29452. if (!data && this._buffer) {
  29453. return; // nothing to do
  29454. }
  29455. data = data || this._data;
  29456. if (!data) {
  29457. return;
  29458. }
  29459. if (!this._buffer) { // create buffer
  29460. if (this._updatable) {
  29461. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29462. this._data = data;
  29463. }
  29464. else {
  29465. this._buffer = this._engine.createVertexBuffer(data);
  29466. }
  29467. }
  29468. else if (this._updatable) { // update buffer
  29469. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29470. this._data = data;
  29471. }
  29472. };
  29473. Buffer.prototype._rebuild = function () {
  29474. this._buffer = null;
  29475. this.create(this._data);
  29476. };
  29477. Buffer.prototype.update = function (data) {
  29478. this.create(data);
  29479. };
  29480. /**
  29481. * Updates the data directly.
  29482. * @param data the new data
  29483. * @param offset the new offset
  29484. * @param vertexCount the vertex count (optional)
  29485. * @param useBytes set to true if the offset is in bytes
  29486. */
  29487. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29488. if (useBytes === void 0) { useBytes = false; }
  29489. if (!this._buffer) {
  29490. return;
  29491. }
  29492. if (this._updatable) { // update buffer
  29493. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29494. this._data = null;
  29495. }
  29496. };
  29497. Buffer.prototype.dispose = function () {
  29498. if (!this._buffer) {
  29499. return;
  29500. }
  29501. if (this._engine._releaseBuffer(this._buffer)) {
  29502. this._buffer = null;
  29503. }
  29504. };
  29505. return Buffer;
  29506. }());
  29507. BABYLON.Buffer = Buffer;
  29508. })(BABYLON || (BABYLON = {}));
  29509. //# sourceMappingURL=babylon.buffer.js.map
  29510. var BABYLON;
  29511. (function (BABYLON) {
  29512. var VertexBuffer = /** @class */ (function () {
  29513. /**
  29514. * Constructor
  29515. * @param engine the engine
  29516. * @param data the data to use for this vertex buffer
  29517. * @param kind the vertex buffer kind
  29518. * @param updatable whether the data is updatable
  29519. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29520. * @param stride the stride (optional)
  29521. * @param instanced whether the buffer is instanced (optional)
  29522. * @param offset the offset of the data (optional)
  29523. * @param size the number of components (optional)
  29524. * @param type the type of the component (optional)
  29525. * @param normalized whether the data contains normalized data (optional)
  29526. * @param useBytes set to true if stride and offset are in bytes (optional)
  29527. */
  29528. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29529. if (normalized === void 0) { normalized = false; }
  29530. if (useBytes === void 0) { useBytes = false; }
  29531. if (data instanceof BABYLON.Buffer) {
  29532. this._buffer = data;
  29533. this._ownsBuffer = false;
  29534. }
  29535. else {
  29536. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29537. this._ownsBuffer = true;
  29538. }
  29539. this._kind = kind;
  29540. if (type == undefined) {
  29541. var data_1 = this.getData();
  29542. this.type = VertexBuffer.FLOAT;
  29543. if (data_1 instanceof Int8Array)
  29544. this.type = VertexBuffer.BYTE;
  29545. else if (data_1 instanceof Uint8Array)
  29546. this.type = VertexBuffer.UNSIGNED_BYTE;
  29547. else if (data_1 instanceof Int16Array)
  29548. this.type = VertexBuffer.SHORT;
  29549. else if (data_1 instanceof Uint16Array)
  29550. this.type = VertexBuffer.UNSIGNED_SHORT;
  29551. else if (data_1 instanceof Int32Array)
  29552. this.type = VertexBuffer.INT;
  29553. else if (data_1 instanceof Uint32Array)
  29554. this.type = VertexBuffer.UNSIGNED_INT;
  29555. }
  29556. else {
  29557. this.type = type;
  29558. }
  29559. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29560. if (useBytes) {
  29561. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29562. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29563. this.byteOffset = offset || 0;
  29564. }
  29565. else {
  29566. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29567. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29568. this.byteOffset = (offset || 0) * typeByteLength;
  29569. }
  29570. this.normalized = normalized;
  29571. this._instanced = instanced !== undefined ? instanced : false;
  29572. this._instanceDivisor = instanced ? 1 : 0;
  29573. }
  29574. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29575. /**
  29576. * Gets or sets the instance divisor when in instanced mode
  29577. */
  29578. get: function () {
  29579. return this._instanceDivisor;
  29580. },
  29581. set: function (value) {
  29582. this._instanceDivisor = value;
  29583. if (value == 0) {
  29584. this._instanced = false;
  29585. }
  29586. else {
  29587. this._instanced = true;
  29588. }
  29589. },
  29590. enumerable: true,
  29591. configurable: true
  29592. });
  29593. VertexBuffer.prototype._rebuild = function () {
  29594. if (!this._buffer) {
  29595. return;
  29596. }
  29597. this._buffer._rebuild();
  29598. };
  29599. /**
  29600. * Returns the kind of the VertexBuffer (string).
  29601. */
  29602. VertexBuffer.prototype.getKind = function () {
  29603. return this._kind;
  29604. };
  29605. // Properties
  29606. /**
  29607. * Boolean : is the VertexBuffer updatable ?
  29608. */
  29609. VertexBuffer.prototype.isUpdatable = function () {
  29610. return this._buffer.isUpdatable();
  29611. };
  29612. /**
  29613. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29614. */
  29615. VertexBuffer.prototype.getData = function () {
  29616. return this._buffer.getData();
  29617. };
  29618. /**
  29619. * Returns the WebGLBuffer associated to the VertexBuffer.
  29620. */
  29621. VertexBuffer.prototype.getBuffer = function () {
  29622. return this._buffer.getBuffer();
  29623. };
  29624. /**
  29625. * Returns the stride as a multiple of the type byte length.
  29626. * DEPRECATED. Use byteStride instead.
  29627. */
  29628. VertexBuffer.prototype.getStrideSize = function () {
  29629. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29630. };
  29631. /**
  29632. * Returns the offset as a multiple of the type byte length.
  29633. * DEPRECATED. Use byteOffset instead.
  29634. */
  29635. VertexBuffer.prototype.getOffset = function () {
  29636. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29637. };
  29638. /**
  29639. * Returns the number of components per vertex attribute (integer).
  29640. */
  29641. VertexBuffer.prototype.getSize = function () {
  29642. return this._size;
  29643. };
  29644. /**
  29645. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29646. */
  29647. VertexBuffer.prototype.getIsInstanced = function () {
  29648. return this._instanced;
  29649. };
  29650. /**
  29651. * Returns the instancing divisor, zero for non-instanced (integer).
  29652. */
  29653. VertexBuffer.prototype.getInstanceDivisor = function () {
  29654. return this._instanceDivisor;
  29655. };
  29656. // Methods
  29657. /**
  29658. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29659. * Returns the created WebGLBuffer.
  29660. */
  29661. VertexBuffer.prototype.create = function (data) {
  29662. return this._buffer.create(data);
  29663. };
  29664. /**
  29665. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29666. * This function will create a new buffer if the current one is not updatable
  29667. * Returns the updated WebGLBuffer.
  29668. */
  29669. VertexBuffer.prototype.update = function (data) {
  29670. return this._buffer.update(data);
  29671. };
  29672. /**
  29673. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29674. * Returns the directly updated WebGLBuffer.
  29675. * @param data the new data
  29676. * @param offset the new offset
  29677. * @param useBytes set to true if the offset is in bytes
  29678. */
  29679. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29680. if (useBytes === void 0) { useBytes = false; }
  29681. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29682. };
  29683. /**
  29684. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29685. */
  29686. VertexBuffer.prototype.dispose = function () {
  29687. if (this._ownsBuffer) {
  29688. this._buffer.dispose();
  29689. }
  29690. };
  29691. /**
  29692. * Enumerates each value of this vertex buffer as numbers.
  29693. * @param count the number of values to enumerate
  29694. * @param callback the callback function called for each value
  29695. */
  29696. VertexBuffer.prototype.forEach = function (count, callback) {
  29697. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29698. };
  29699. Object.defineProperty(VertexBuffer, "PositionKind", {
  29700. get: function () {
  29701. return VertexBuffer._PositionKind;
  29702. },
  29703. enumerable: true,
  29704. configurable: true
  29705. });
  29706. Object.defineProperty(VertexBuffer, "NormalKind", {
  29707. get: function () {
  29708. return VertexBuffer._NormalKind;
  29709. },
  29710. enumerable: true,
  29711. configurable: true
  29712. });
  29713. Object.defineProperty(VertexBuffer, "TangentKind", {
  29714. get: function () {
  29715. return VertexBuffer._TangentKind;
  29716. },
  29717. enumerable: true,
  29718. configurable: true
  29719. });
  29720. Object.defineProperty(VertexBuffer, "UVKind", {
  29721. get: function () {
  29722. return VertexBuffer._UVKind;
  29723. },
  29724. enumerable: true,
  29725. configurable: true
  29726. });
  29727. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29728. get: function () {
  29729. return VertexBuffer._UV2Kind;
  29730. },
  29731. enumerable: true,
  29732. configurable: true
  29733. });
  29734. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29735. get: function () {
  29736. return VertexBuffer._UV3Kind;
  29737. },
  29738. enumerable: true,
  29739. configurable: true
  29740. });
  29741. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29742. get: function () {
  29743. return VertexBuffer._UV4Kind;
  29744. },
  29745. enumerable: true,
  29746. configurable: true
  29747. });
  29748. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29749. get: function () {
  29750. return VertexBuffer._UV5Kind;
  29751. },
  29752. enumerable: true,
  29753. configurable: true
  29754. });
  29755. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29756. get: function () {
  29757. return VertexBuffer._UV6Kind;
  29758. },
  29759. enumerable: true,
  29760. configurable: true
  29761. });
  29762. Object.defineProperty(VertexBuffer, "ColorKind", {
  29763. get: function () {
  29764. return VertexBuffer._ColorKind;
  29765. },
  29766. enumerable: true,
  29767. configurable: true
  29768. });
  29769. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29770. get: function () {
  29771. return VertexBuffer._MatricesIndicesKind;
  29772. },
  29773. enumerable: true,
  29774. configurable: true
  29775. });
  29776. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29777. get: function () {
  29778. return VertexBuffer._MatricesWeightsKind;
  29779. },
  29780. enumerable: true,
  29781. configurable: true
  29782. });
  29783. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29784. get: function () {
  29785. return VertexBuffer._MatricesIndicesExtraKind;
  29786. },
  29787. enumerable: true,
  29788. configurable: true
  29789. });
  29790. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29791. get: function () {
  29792. return VertexBuffer._MatricesWeightsExtraKind;
  29793. },
  29794. enumerable: true,
  29795. configurable: true
  29796. });
  29797. /**
  29798. * Deduces the stride given a kind.
  29799. * @param kind The kind string to deduce
  29800. * @returns The deduced stride
  29801. */
  29802. VertexBuffer.DeduceStride = function (kind) {
  29803. switch (kind) {
  29804. case VertexBuffer.UVKind:
  29805. case VertexBuffer.UV2Kind:
  29806. case VertexBuffer.UV3Kind:
  29807. case VertexBuffer.UV4Kind:
  29808. case VertexBuffer.UV5Kind:
  29809. case VertexBuffer.UV6Kind:
  29810. return 2;
  29811. case VertexBuffer.NormalKind:
  29812. case VertexBuffer.PositionKind:
  29813. return 3;
  29814. case VertexBuffer.ColorKind:
  29815. case VertexBuffer.MatricesIndicesKind:
  29816. case VertexBuffer.MatricesIndicesExtraKind:
  29817. case VertexBuffer.MatricesWeightsKind:
  29818. case VertexBuffer.MatricesWeightsExtraKind:
  29819. case VertexBuffer.TangentKind:
  29820. return 4;
  29821. default:
  29822. throw new Error("Invalid kind '" + kind + "'");
  29823. }
  29824. };
  29825. /**
  29826. * Gets the byte length of the given type.
  29827. * @param type the type
  29828. * @returns the number of bytes
  29829. */
  29830. VertexBuffer.GetTypeByteLength = function (type) {
  29831. switch (type) {
  29832. case VertexBuffer.BYTE:
  29833. case VertexBuffer.UNSIGNED_BYTE:
  29834. return 1;
  29835. case VertexBuffer.SHORT:
  29836. case VertexBuffer.UNSIGNED_SHORT:
  29837. return 2;
  29838. case VertexBuffer.INT:
  29839. case VertexBuffer.FLOAT:
  29840. return 4;
  29841. default:
  29842. throw new Error("Invalid type '" + type + "'");
  29843. }
  29844. };
  29845. /**
  29846. * Enumerates each value of the given parameters as numbers.
  29847. * @param data the data to enumerate
  29848. * @param byteOffset the byte offset of the data
  29849. * @param byteStride the byte stride of the data
  29850. * @param componentCount the number of components per element
  29851. * @param componentType the type of the component
  29852. * @param count the total number of components
  29853. * @param normalized whether the data is normalized
  29854. * @param callback the callback function called for each value
  29855. */
  29856. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29857. if (data instanceof Array) {
  29858. var offset = byteOffset / 4;
  29859. var stride = byteStride / 4;
  29860. for (var index = 0; index < count; index += componentCount) {
  29861. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29862. callback(data[offset + componentIndex], index + componentIndex);
  29863. }
  29864. offset += stride;
  29865. }
  29866. }
  29867. else {
  29868. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29869. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29870. for (var index = 0; index < count; index += componentCount) {
  29871. var componentByteOffset = byteOffset;
  29872. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29873. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29874. callback(value, index + componentIndex);
  29875. componentByteOffset += componentByteLength;
  29876. }
  29877. byteOffset += byteStride;
  29878. }
  29879. }
  29880. };
  29881. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29882. switch (type) {
  29883. case VertexBuffer.BYTE: {
  29884. var value = dataView.getInt8(byteOffset);
  29885. if (normalized) {
  29886. value = Math.max(value / 127, -1);
  29887. }
  29888. return value;
  29889. }
  29890. case VertexBuffer.UNSIGNED_BYTE: {
  29891. var value = dataView.getUint8(byteOffset);
  29892. if (normalized) {
  29893. value = value / 255;
  29894. }
  29895. return value;
  29896. }
  29897. case VertexBuffer.SHORT: {
  29898. var value = dataView.getInt16(byteOffset, true);
  29899. if (normalized) {
  29900. value = Math.max(value / 16383, -1);
  29901. }
  29902. return value;
  29903. }
  29904. case VertexBuffer.UNSIGNED_SHORT: {
  29905. var value = dataView.getUint16(byteOffset, true);
  29906. if (normalized) {
  29907. value = value / 65535;
  29908. }
  29909. return value;
  29910. }
  29911. case VertexBuffer.FLOAT: {
  29912. return dataView.getFloat32(byteOffset, true);
  29913. }
  29914. default: {
  29915. throw new Error("Invalid component type " + type);
  29916. }
  29917. }
  29918. };
  29919. /**
  29920. * The byte type.
  29921. */
  29922. VertexBuffer.BYTE = 5120;
  29923. /**
  29924. * The unsigned byte type.
  29925. */
  29926. VertexBuffer.UNSIGNED_BYTE = 5121;
  29927. /**
  29928. * The short type.
  29929. */
  29930. VertexBuffer.SHORT = 5122;
  29931. /**
  29932. * The unsigned short type.
  29933. */
  29934. VertexBuffer.UNSIGNED_SHORT = 5123;
  29935. /**
  29936. * The integer type.
  29937. */
  29938. VertexBuffer.INT = 5124;
  29939. /**
  29940. * The unsigned integer type.
  29941. */
  29942. VertexBuffer.UNSIGNED_INT = 5125;
  29943. /**
  29944. * The float type.
  29945. */
  29946. VertexBuffer.FLOAT = 5126;
  29947. // Enums
  29948. VertexBuffer._PositionKind = "position";
  29949. VertexBuffer._NormalKind = "normal";
  29950. VertexBuffer._TangentKind = "tangent";
  29951. VertexBuffer._UVKind = "uv";
  29952. VertexBuffer._UV2Kind = "uv2";
  29953. VertexBuffer._UV3Kind = "uv3";
  29954. VertexBuffer._UV4Kind = "uv4";
  29955. VertexBuffer._UV5Kind = "uv5";
  29956. VertexBuffer._UV6Kind = "uv6";
  29957. VertexBuffer._ColorKind = "color";
  29958. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29959. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29960. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29961. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29962. return VertexBuffer;
  29963. }());
  29964. BABYLON.VertexBuffer = VertexBuffer;
  29965. })(BABYLON || (BABYLON = {}));
  29966. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29967. var BABYLON;
  29968. (function (BABYLON) {
  29969. /**
  29970. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29971. */
  29972. var DummyInternalTextureTracker = /** @class */ (function () {
  29973. function DummyInternalTextureTracker() {
  29974. /**
  29975. * Gets or set the previous tracker in the list
  29976. */
  29977. this.previous = null;
  29978. /**
  29979. * Gets or set the next tracker in the list
  29980. */
  29981. this.next = null;
  29982. }
  29983. return DummyInternalTextureTracker;
  29984. }());
  29985. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29986. })(BABYLON || (BABYLON = {}));
  29987. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29988. var BABYLON;
  29989. (function (BABYLON) {
  29990. /**
  29991. * Class used to store data associated with WebGL texture data for the engine
  29992. * This class should not be used directly
  29993. */
  29994. var InternalTexture = /** @class */ (function () {
  29995. /**
  29996. * Creates a new InternalTexture
  29997. * @param engine defines the engine to use
  29998. * @param dataSource defines the type of data that will be used
  29999. */
  30000. function InternalTexture(engine, dataSource) {
  30001. /**
  30002. * Observable called when the texture is loaded
  30003. */
  30004. this.onLoadedObservable = new BABYLON.Observable();
  30005. /**
  30006. * Gets or set the previous tracker in the list
  30007. */
  30008. this.previous = null;
  30009. /**
  30010. * Gets or set the next tracker in the list
  30011. */
  30012. this.next = null;
  30013. // Private
  30014. /** @hidden */
  30015. this._initialSlot = -1;
  30016. /** @hidden */
  30017. this._designatedSlot = -1;
  30018. /** @hidden */
  30019. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30020. /** @hidden */
  30021. this._comparisonFunction = 0;
  30022. /** @hidden */
  30023. this._references = 1;
  30024. this._engine = engine;
  30025. this._dataSource = dataSource;
  30026. this._webGLTexture = engine._createTexture();
  30027. }
  30028. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30029. /**
  30030. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30031. */
  30032. get: function () {
  30033. return this._dataSource;
  30034. },
  30035. enumerable: true,
  30036. configurable: true
  30037. });
  30038. /**
  30039. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30040. */
  30041. InternalTexture.prototype.incrementReferences = function () {
  30042. this._references++;
  30043. };
  30044. /**
  30045. * Change the size of the texture (not the size of the content)
  30046. * @param width defines the new width
  30047. * @param height defines the new height
  30048. * @param depth defines the new depth (1 by default)
  30049. */
  30050. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30051. if (depth === void 0) { depth = 1; }
  30052. this.width = width;
  30053. this.height = height;
  30054. this.depth = depth;
  30055. this.baseWidth = width;
  30056. this.baseHeight = height;
  30057. this.baseDepth = depth;
  30058. this._size = width * height * depth;
  30059. };
  30060. /** @hidden */
  30061. InternalTexture.prototype._rebuild = function () {
  30062. var _this = this;
  30063. var proxy;
  30064. this.isReady = false;
  30065. this._cachedCoordinatesMode = null;
  30066. this._cachedWrapU = null;
  30067. this._cachedWrapV = null;
  30068. this._cachedAnisotropicFilteringLevel = null;
  30069. switch (this._dataSource) {
  30070. case InternalTexture.DATASOURCE_TEMP:
  30071. return;
  30072. case InternalTexture.DATASOURCE_URL:
  30073. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30074. _this.isReady = true;
  30075. }, null, this._buffer, undefined, this.format);
  30076. proxy._swapAndDie(this);
  30077. return;
  30078. case InternalTexture.DATASOURCE_RAW:
  30079. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30080. proxy._swapAndDie(this);
  30081. this.isReady = true;
  30082. return;
  30083. case InternalTexture.DATASOURCE_RAW3D:
  30084. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30085. proxy._swapAndDie(this);
  30086. this.isReady = true;
  30087. return;
  30088. case InternalTexture.DATASOURCE_DYNAMIC:
  30089. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30090. proxy._swapAndDie(this);
  30091. // The engine will make sure to update content so no need to flag it as isReady = true
  30092. return;
  30093. case InternalTexture.DATASOURCE_RENDERTARGET:
  30094. var options = new BABYLON.RenderTargetCreationOptions();
  30095. options.generateDepthBuffer = this._generateDepthBuffer;
  30096. options.generateMipMaps = this.generateMipMaps;
  30097. options.generateStencilBuffer = this._generateStencilBuffer;
  30098. options.samplingMode = this.samplingMode;
  30099. options.type = this.type;
  30100. if (this.isCube) {
  30101. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30102. }
  30103. else {
  30104. var size = {
  30105. width: this.width,
  30106. height: this.height
  30107. };
  30108. proxy = this._engine.createRenderTargetTexture(size, options);
  30109. }
  30110. proxy._swapAndDie(this);
  30111. this.isReady = true;
  30112. return;
  30113. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30114. var depthTextureOptions = {
  30115. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30116. comparisonFunction: this._comparisonFunction,
  30117. generateStencil: this._generateStencilBuffer,
  30118. isCube: this.isCube
  30119. };
  30120. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30121. proxy._swapAndDie(this);
  30122. this.isReady = true;
  30123. return;
  30124. case InternalTexture.DATASOURCE_CUBE:
  30125. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30126. _this.isReady = true;
  30127. }, null, this.format, this._extension);
  30128. proxy._swapAndDie(this);
  30129. return;
  30130. case InternalTexture.DATASOURCE_CUBERAW:
  30131. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30132. proxy._swapAndDie(this);
  30133. this.isReady = true;
  30134. return;
  30135. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30136. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30137. if (proxy) {
  30138. proxy._swapAndDie(_this);
  30139. }
  30140. _this.isReady = true;
  30141. }, null, this.format, this._extension);
  30142. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30143. return;
  30144. }
  30145. };
  30146. InternalTexture.prototype._swapAndDie = function (target) {
  30147. target._webGLTexture = this._webGLTexture;
  30148. if (this._framebuffer) {
  30149. target._framebuffer = this._framebuffer;
  30150. }
  30151. if (this._depthStencilBuffer) {
  30152. target._depthStencilBuffer = this._depthStencilBuffer;
  30153. }
  30154. if (this._lodTextureHigh) {
  30155. if (target._lodTextureHigh) {
  30156. target._lodTextureHigh.dispose();
  30157. }
  30158. target._lodTextureHigh = this._lodTextureHigh;
  30159. }
  30160. if (this._lodTextureMid) {
  30161. if (target._lodTextureMid) {
  30162. target._lodTextureMid.dispose();
  30163. }
  30164. target._lodTextureMid = this._lodTextureMid;
  30165. }
  30166. if (this._lodTextureLow) {
  30167. if (target._lodTextureLow) {
  30168. target._lodTextureLow.dispose();
  30169. }
  30170. target._lodTextureLow = this._lodTextureLow;
  30171. }
  30172. var cache = this._engine.getLoadedTexturesCache();
  30173. var index = cache.indexOf(this);
  30174. if (index !== -1) {
  30175. cache.splice(index, 1);
  30176. }
  30177. };
  30178. /**
  30179. * Dispose the current allocated resources
  30180. */
  30181. InternalTexture.prototype.dispose = function () {
  30182. if (!this._webGLTexture) {
  30183. return;
  30184. }
  30185. this._references--;
  30186. if (this._references === 0) {
  30187. this._engine._releaseTexture(this);
  30188. this._webGLTexture = null;
  30189. this.previous = null;
  30190. this.next = null;
  30191. }
  30192. };
  30193. /**
  30194. * The source of the texture data is unknown
  30195. */
  30196. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30197. /**
  30198. * Texture data comes from an URL
  30199. */
  30200. InternalTexture.DATASOURCE_URL = 1;
  30201. /**
  30202. * Texture data is only used for temporary storage
  30203. */
  30204. InternalTexture.DATASOURCE_TEMP = 2;
  30205. /**
  30206. * Texture data comes from raw data (ArrayBuffer)
  30207. */
  30208. InternalTexture.DATASOURCE_RAW = 3;
  30209. /**
  30210. * Texture content is dynamic (video or dynamic texture)
  30211. */
  30212. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30213. /**
  30214. * Texture content is generated by rendering to it
  30215. */
  30216. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30217. /**
  30218. * Texture content is part of a multi render target process
  30219. */
  30220. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30221. /**
  30222. * Texture data comes from a cube data file
  30223. */
  30224. InternalTexture.DATASOURCE_CUBE = 7;
  30225. /**
  30226. * Texture data comes from a raw cube data
  30227. */
  30228. InternalTexture.DATASOURCE_CUBERAW = 8;
  30229. /**
  30230. * Texture data come from a prefiltered cube data file
  30231. */
  30232. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30233. /**
  30234. * Texture content is raw 3D data
  30235. */
  30236. InternalTexture.DATASOURCE_RAW3D = 10;
  30237. /**
  30238. * Texture content is a depth texture
  30239. */
  30240. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30241. return InternalTexture;
  30242. }());
  30243. BABYLON.InternalTexture = InternalTexture;
  30244. })(BABYLON || (BABYLON = {}));
  30245. //# sourceMappingURL=babylon.internalTexture.js.map
  30246. var BABYLON;
  30247. (function (BABYLON) {
  30248. var BaseTexture = /** @class */ (function () {
  30249. function BaseTexture(scene) {
  30250. this._hasAlpha = false;
  30251. this.getAlphaFromRGB = false;
  30252. this.level = 1;
  30253. this.coordinatesIndex = 0;
  30254. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30255. /**
  30256. * | Value | Type | Description |
  30257. * | ----- | ------------------ | ----------- |
  30258. * | 0 | CLAMP_ADDRESSMODE | |
  30259. * | 1 | WRAP_ADDRESSMODE | |
  30260. * | 2 | MIRROR_ADDRESSMODE | |
  30261. */
  30262. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30263. /**
  30264. * | Value | Type | Description |
  30265. * | ----- | ------------------ | ----------- |
  30266. * | 0 | CLAMP_ADDRESSMODE | |
  30267. * | 1 | WRAP_ADDRESSMODE | |
  30268. * | 2 | MIRROR_ADDRESSMODE | |
  30269. */
  30270. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30271. /**
  30272. * | Value | Type | Description |
  30273. * | ----- | ------------------ | ----------- |
  30274. * | 0 | CLAMP_ADDRESSMODE | |
  30275. * | 1 | WRAP_ADDRESSMODE | |
  30276. * | 2 | MIRROR_ADDRESSMODE | |
  30277. */
  30278. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30279. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30280. this.isCube = false;
  30281. this.is3D = false;
  30282. this.gammaSpace = true;
  30283. this.invertZ = false;
  30284. this.lodLevelInAlpha = false;
  30285. this.lodGenerationOffset = 0.0;
  30286. this.lodGenerationScale = 0.8;
  30287. this.isRenderTarget = false;
  30288. this.animations = new Array();
  30289. /**
  30290. * An event triggered when the texture is disposed.
  30291. */
  30292. this.onDisposeObservable = new BABYLON.Observable();
  30293. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30294. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30295. if (this._scene) {
  30296. this._scene.textures.push(this);
  30297. }
  30298. this._uid = null;
  30299. }
  30300. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30301. get: function () {
  30302. return this._hasAlpha;
  30303. },
  30304. set: function (value) {
  30305. if (this._hasAlpha === value) {
  30306. return;
  30307. }
  30308. this._hasAlpha = value;
  30309. if (this._scene) {
  30310. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30311. }
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30317. get: function () {
  30318. return this._coordinatesMode;
  30319. },
  30320. /**
  30321. * How a texture is mapped.
  30322. *
  30323. * | Value | Type | Description |
  30324. * | ----- | ----------------------------------- | ----------- |
  30325. * | 0 | EXPLICIT_MODE | |
  30326. * | 1 | SPHERICAL_MODE | |
  30327. * | 2 | PLANAR_MODE | |
  30328. * | 3 | CUBIC_MODE | |
  30329. * | 4 | PROJECTION_MODE | |
  30330. * | 5 | SKYBOX_MODE | |
  30331. * | 6 | INVCUBIC_MODE | |
  30332. * | 7 | EQUIRECTANGULAR_MODE | |
  30333. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30334. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30335. */
  30336. set: function (value) {
  30337. if (this._coordinatesMode === value) {
  30338. return;
  30339. }
  30340. this._coordinatesMode = value;
  30341. if (this._scene) {
  30342. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30343. }
  30344. },
  30345. enumerable: true,
  30346. configurable: true
  30347. });
  30348. Object.defineProperty(BaseTexture.prototype, "uid", {
  30349. get: function () {
  30350. if (!this._uid) {
  30351. this._uid = BABYLON.Tools.RandomId();
  30352. }
  30353. return this._uid;
  30354. },
  30355. enumerable: true,
  30356. configurable: true
  30357. });
  30358. BaseTexture.prototype.toString = function () {
  30359. return this.name;
  30360. };
  30361. BaseTexture.prototype.getClassName = function () {
  30362. return "BaseTexture";
  30363. };
  30364. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30365. set: function (callback) {
  30366. if (this._onDisposeObserver) {
  30367. this.onDisposeObservable.remove(this._onDisposeObserver);
  30368. }
  30369. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30370. },
  30371. enumerable: true,
  30372. configurable: true
  30373. });
  30374. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30375. get: function () {
  30376. return true;
  30377. },
  30378. enumerable: true,
  30379. configurable: true
  30380. });
  30381. BaseTexture.prototype.getScene = function () {
  30382. return this._scene;
  30383. };
  30384. BaseTexture.prototype.getTextureMatrix = function () {
  30385. return BABYLON.Matrix.IdentityReadOnly;
  30386. };
  30387. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30388. return BABYLON.Matrix.IdentityReadOnly;
  30389. };
  30390. BaseTexture.prototype.getInternalTexture = function () {
  30391. return this._texture;
  30392. };
  30393. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30394. return !this.isBlocking || this.isReady();
  30395. };
  30396. BaseTexture.prototype.isReady = function () {
  30397. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30398. this.delayLoad();
  30399. return false;
  30400. }
  30401. if (this._texture) {
  30402. return this._texture.isReady;
  30403. }
  30404. return false;
  30405. };
  30406. BaseTexture.prototype.getSize = function () {
  30407. if (this._texture && this._texture.width) {
  30408. return new BABYLON.Size(this._texture.width, this._texture.height);
  30409. }
  30410. if (this._texture && this._texture._size) {
  30411. return new BABYLON.Size(this._texture._size, this._texture._size);
  30412. }
  30413. return BABYLON.Size.Zero();
  30414. };
  30415. BaseTexture.prototype.getBaseSize = function () {
  30416. if (!this.isReady() || !this._texture)
  30417. return BABYLON.Size.Zero();
  30418. if (this._texture._size) {
  30419. return new BABYLON.Size(this._texture._size, this._texture._size);
  30420. }
  30421. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30422. };
  30423. BaseTexture.prototype.scale = function (ratio) {
  30424. };
  30425. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30426. get: function () {
  30427. return false;
  30428. },
  30429. enumerable: true,
  30430. configurable: true
  30431. });
  30432. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30433. if (!this._scene) {
  30434. return null;
  30435. }
  30436. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30437. for (var index = 0; index < texturesCache.length; index++) {
  30438. var texturesCacheEntry = texturesCache[index];
  30439. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30440. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30441. texturesCacheEntry.incrementReferences();
  30442. return texturesCacheEntry;
  30443. }
  30444. }
  30445. }
  30446. return null;
  30447. };
  30448. BaseTexture.prototype._rebuild = function () {
  30449. };
  30450. BaseTexture.prototype.delayLoad = function () {
  30451. };
  30452. BaseTexture.prototype.clone = function () {
  30453. return null;
  30454. };
  30455. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30456. get: function () {
  30457. if (!this._texture) {
  30458. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30459. }
  30460. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30461. },
  30462. enumerable: true,
  30463. configurable: true
  30464. });
  30465. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30466. get: function () {
  30467. if (!this._texture) {
  30468. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30469. }
  30470. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30471. },
  30472. enumerable: true,
  30473. configurable: true
  30474. });
  30475. BaseTexture.prototype.readPixels = function (faceIndex) {
  30476. if (faceIndex === void 0) { faceIndex = 0; }
  30477. if (!this._texture) {
  30478. return null;
  30479. }
  30480. var size = this.getSize();
  30481. var scene = this.getScene();
  30482. if (!scene) {
  30483. return null;
  30484. }
  30485. var engine = scene.getEngine();
  30486. if (this._texture.isCube) {
  30487. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30488. }
  30489. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30490. };
  30491. BaseTexture.prototype.releaseInternalTexture = function () {
  30492. if (this._texture) {
  30493. this._texture.dispose();
  30494. this._texture = null;
  30495. }
  30496. };
  30497. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30498. get: function () {
  30499. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30500. return null;
  30501. }
  30502. if (!this._texture._sphericalPolynomial) {
  30503. this._texture._sphericalPolynomial =
  30504. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30505. }
  30506. return this._texture._sphericalPolynomial;
  30507. },
  30508. set: function (value) {
  30509. if (this._texture) {
  30510. this._texture._sphericalPolynomial = value;
  30511. }
  30512. },
  30513. enumerable: true,
  30514. configurable: true
  30515. });
  30516. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30517. get: function () {
  30518. if (this._texture) {
  30519. return this._texture._lodTextureHigh;
  30520. }
  30521. return null;
  30522. },
  30523. enumerable: true,
  30524. configurable: true
  30525. });
  30526. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30527. get: function () {
  30528. if (this._texture) {
  30529. return this._texture._lodTextureMid;
  30530. }
  30531. return null;
  30532. },
  30533. enumerable: true,
  30534. configurable: true
  30535. });
  30536. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30537. get: function () {
  30538. if (this._texture) {
  30539. return this._texture._lodTextureLow;
  30540. }
  30541. return null;
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. BaseTexture.prototype.dispose = function () {
  30547. if (!this._scene) {
  30548. return;
  30549. }
  30550. // Animations
  30551. this._scene.stopAnimation(this);
  30552. // Remove from scene
  30553. this._scene._removePendingData(this);
  30554. var index = this._scene.textures.indexOf(this);
  30555. if (index >= 0) {
  30556. this._scene.textures.splice(index, 1);
  30557. }
  30558. if (this._texture === undefined) {
  30559. return;
  30560. }
  30561. // Release
  30562. this.releaseInternalTexture();
  30563. // Callback
  30564. this.onDisposeObservable.notifyObservers(this);
  30565. this.onDisposeObservable.clear();
  30566. };
  30567. BaseTexture.prototype.serialize = function () {
  30568. if (!this.name) {
  30569. return null;
  30570. }
  30571. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30572. // Animations
  30573. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30574. return serializationObject;
  30575. };
  30576. BaseTexture.WhenAllReady = function (textures, callback) {
  30577. var numRemaining = textures.length;
  30578. if (numRemaining === 0) {
  30579. callback();
  30580. return;
  30581. }
  30582. var _loop_1 = function () {
  30583. texture = textures[i];
  30584. if (texture.isReady()) {
  30585. if (--numRemaining === 0) {
  30586. callback();
  30587. }
  30588. }
  30589. else {
  30590. onLoadObservable = texture.onLoadObservable;
  30591. var onLoadCallback_1 = function () {
  30592. onLoadObservable.removeCallback(onLoadCallback_1);
  30593. if (--numRemaining === 0) {
  30594. callback();
  30595. }
  30596. };
  30597. onLoadObservable.add(onLoadCallback_1);
  30598. }
  30599. };
  30600. var texture, onLoadObservable;
  30601. for (var i = 0; i < textures.length; i++) {
  30602. _loop_1();
  30603. }
  30604. };
  30605. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30606. __decorate([
  30607. BABYLON.serialize()
  30608. ], BaseTexture.prototype, "name", void 0);
  30609. __decorate([
  30610. BABYLON.serialize("hasAlpha")
  30611. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30612. __decorate([
  30613. BABYLON.serialize()
  30614. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30615. __decorate([
  30616. BABYLON.serialize()
  30617. ], BaseTexture.prototype, "level", void 0);
  30618. __decorate([
  30619. BABYLON.serialize()
  30620. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30621. __decorate([
  30622. BABYLON.serialize("coordinatesMode")
  30623. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30624. __decorate([
  30625. BABYLON.serialize()
  30626. ], BaseTexture.prototype, "wrapU", void 0);
  30627. __decorate([
  30628. BABYLON.serialize()
  30629. ], BaseTexture.prototype, "wrapV", void 0);
  30630. __decorate([
  30631. BABYLON.serialize()
  30632. ], BaseTexture.prototype, "wrapR", void 0);
  30633. __decorate([
  30634. BABYLON.serialize()
  30635. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30636. __decorate([
  30637. BABYLON.serialize()
  30638. ], BaseTexture.prototype, "isCube", void 0);
  30639. __decorate([
  30640. BABYLON.serialize()
  30641. ], BaseTexture.prototype, "is3D", void 0);
  30642. __decorate([
  30643. BABYLON.serialize()
  30644. ], BaseTexture.prototype, "gammaSpace", void 0);
  30645. __decorate([
  30646. BABYLON.serialize()
  30647. ], BaseTexture.prototype, "invertZ", void 0);
  30648. __decorate([
  30649. BABYLON.serialize()
  30650. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30651. __decorate([
  30652. BABYLON.serialize()
  30653. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30654. __decorate([
  30655. BABYLON.serialize()
  30656. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30657. __decorate([
  30658. BABYLON.serialize()
  30659. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30660. return BaseTexture;
  30661. }());
  30662. BABYLON.BaseTexture = BaseTexture;
  30663. })(BABYLON || (BABYLON = {}));
  30664. //# sourceMappingURL=babylon.baseTexture.js.map
  30665. var BABYLON;
  30666. (function (BABYLON) {
  30667. var Texture = /** @class */ (function (_super) {
  30668. __extends(Texture, _super);
  30669. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30670. if (noMipmap === void 0) { noMipmap = false; }
  30671. if (invertY === void 0) { invertY = true; }
  30672. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30673. if (onLoad === void 0) { onLoad = null; }
  30674. if (onError === void 0) { onError = null; }
  30675. if (buffer === void 0) { buffer = null; }
  30676. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30677. var _this = _super.call(this, scene) || this;
  30678. _this.uOffset = 0;
  30679. _this.vOffset = 0;
  30680. _this.uScale = 1.0;
  30681. _this.vScale = 1.0;
  30682. _this.uAng = 0;
  30683. _this.vAng = 0;
  30684. _this.wAng = 0;
  30685. /**
  30686. * Defines the center of rotation (U)
  30687. */
  30688. _this.uRotationCenter = 0.5;
  30689. /**
  30690. * Defines the center of rotation (V)
  30691. */
  30692. _this.vRotationCenter = 0.5;
  30693. /**
  30694. * Defines the center of rotation (W)
  30695. */
  30696. _this.wRotationCenter = 0.5;
  30697. _this._isBlocking = true;
  30698. _this.name = url || "";
  30699. _this.url = url;
  30700. _this._noMipmap = noMipmap;
  30701. _this._invertY = invertY;
  30702. _this._samplingMode = samplingMode;
  30703. _this._buffer = buffer;
  30704. _this._deleteBuffer = deleteBuffer;
  30705. if (format) {
  30706. _this._format = format;
  30707. }
  30708. scene = _this.getScene();
  30709. if (!scene) {
  30710. return _this;
  30711. }
  30712. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30713. var load = function () {
  30714. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30715. _this.onLoadObservable.notifyObservers(_this);
  30716. }
  30717. if (onLoad) {
  30718. onLoad();
  30719. }
  30720. if (!_this.isBlocking && scene) {
  30721. scene.resetCachedMaterial();
  30722. }
  30723. };
  30724. if (!_this.url) {
  30725. _this._delayedOnLoad = load;
  30726. _this._delayedOnError = onError;
  30727. return _this;
  30728. }
  30729. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30730. if (!_this._texture) {
  30731. if (!scene.useDelayedTextureLoading) {
  30732. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30733. if (deleteBuffer) {
  30734. delete _this._buffer;
  30735. }
  30736. }
  30737. else {
  30738. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30739. _this._delayedOnLoad = load;
  30740. _this._delayedOnError = onError;
  30741. }
  30742. }
  30743. else {
  30744. if (_this._texture.isReady) {
  30745. BABYLON.Tools.SetImmediate(function () { return load(); });
  30746. }
  30747. else {
  30748. _this._texture.onLoadedObservable.add(load);
  30749. }
  30750. }
  30751. return _this;
  30752. }
  30753. Object.defineProperty(Texture.prototype, "noMipmap", {
  30754. get: function () {
  30755. return this._noMipmap;
  30756. },
  30757. enumerable: true,
  30758. configurable: true
  30759. });
  30760. Object.defineProperty(Texture.prototype, "isBlocking", {
  30761. get: function () {
  30762. return this._isBlocking;
  30763. },
  30764. set: function (value) {
  30765. this._isBlocking = value;
  30766. },
  30767. enumerable: true,
  30768. configurable: true
  30769. });
  30770. Object.defineProperty(Texture.prototype, "samplingMode", {
  30771. get: function () {
  30772. return this._samplingMode;
  30773. },
  30774. enumerable: true,
  30775. configurable: true
  30776. });
  30777. /**
  30778. * Update the url (and optional buffer) of this texture if url was null during construction.
  30779. * @param url the url of the texture
  30780. * @param buffer the buffer of the texture (defaults to null)
  30781. */
  30782. Texture.prototype.updateURL = function (url, buffer) {
  30783. if (buffer === void 0) { buffer = null; }
  30784. if (this.url) {
  30785. throw new Error("URL is already set");
  30786. }
  30787. this.url = url;
  30788. this._buffer = buffer;
  30789. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30790. this.delayLoad();
  30791. };
  30792. Texture.prototype.delayLoad = function () {
  30793. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30794. return;
  30795. }
  30796. var scene = this.getScene();
  30797. if (!scene) {
  30798. return;
  30799. }
  30800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30801. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30802. if (!this._texture) {
  30803. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30804. if (this._deleteBuffer) {
  30805. delete this._buffer;
  30806. }
  30807. }
  30808. else {
  30809. if (this._delayedOnLoad) {
  30810. if (this._texture.isReady) {
  30811. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30812. }
  30813. else {
  30814. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30815. }
  30816. }
  30817. }
  30818. this._delayedOnLoad = null;
  30819. this._delayedOnError = null;
  30820. };
  30821. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30822. if (!this._texture) {
  30823. return;
  30824. }
  30825. var scene = this.getScene();
  30826. if (!scene) {
  30827. return;
  30828. }
  30829. this._samplingMode = samplingMode;
  30830. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30831. };
  30832. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30833. x *= this.uScale;
  30834. y *= this.vScale;
  30835. x -= this.uRotationCenter * this.uScale;
  30836. y -= this.vRotationCenter * this.vScale;
  30837. z -= this.wRotationCenter;
  30838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30839. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30840. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30841. t.z += this.wRotationCenter;
  30842. };
  30843. Texture.prototype.getTextureMatrix = function () {
  30844. var _this = this;
  30845. if (this.uOffset === this._cachedUOffset &&
  30846. this.vOffset === this._cachedVOffset &&
  30847. this.uScale === this._cachedUScale &&
  30848. this.vScale === this._cachedVScale &&
  30849. this.uAng === this._cachedUAng &&
  30850. this.vAng === this._cachedVAng &&
  30851. this.wAng === this._cachedWAng) {
  30852. return this._cachedTextureMatrix;
  30853. }
  30854. this._cachedUOffset = this.uOffset;
  30855. this._cachedVOffset = this.vOffset;
  30856. this._cachedUScale = this.uScale;
  30857. this._cachedVScale = this.vScale;
  30858. this._cachedUAng = this.uAng;
  30859. this._cachedVAng = this.vAng;
  30860. this._cachedWAng = this.wAng;
  30861. if (!this._cachedTextureMatrix) {
  30862. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30863. this._rowGenerationMatrix = new BABYLON.Matrix();
  30864. this._t0 = BABYLON.Vector3.Zero();
  30865. this._t1 = BABYLON.Vector3.Zero();
  30866. this._t2 = BABYLON.Vector3.Zero();
  30867. }
  30868. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30869. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30870. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30871. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30872. this._t1.subtractInPlace(this._t0);
  30873. this._t2.subtractInPlace(this._t0);
  30874. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30875. this._cachedTextureMatrix.m[0] = this._t1.x;
  30876. this._cachedTextureMatrix.m[1] = this._t1.y;
  30877. this._cachedTextureMatrix.m[2] = this._t1.z;
  30878. this._cachedTextureMatrix.m[4] = this._t2.x;
  30879. this._cachedTextureMatrix.m[5] = this._t2.y;
  30880. this._cachedTextureMatrix.m[6] = this._t2.z;
  30881. this._cachedTextureMatrix.m[8] = this._t0.x;
  30882. this._cachedTextureMatrix.m[9] = this._t0.y;
  30883. this._cachedTextureMatrix.m[10] = this._t0.z;
  30884. var scene = this.getScene();
  30885. if (!scene) {
  30886. return this._cachedTextureMatrix;
  30887. }
  30888. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30889. return mat.hasTexture(_this);
  30890. });
  30891. return this._cachedTextureMatrix;
  30892. };
  30893. Texture.prototype.getReflectionTextureMatrix = function () {
  30894. var _this = this;
  30895. var scene = this.getScene();
  30896. if (!scene) {
  30897. return this._cachedTextureMatrix;
  30898. }
  30899. if (this.uOffset === this._cachedUOffset &&
  30900. this.vOffset === this._cachedVOffset &&
  30901. this.uScale === this._cachedUScale &&
  30902. this.vScale === this._cachedVScale &&
  30903. this.coordinatesMode === this._cachedCoordinatesMode) {
  30904. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30905. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30906. return this._cachedTextureMatrix;
  30907. }
  30908. }
  30909. else {
  30910. return this._cachedTextureMatrix;
  30911. }
  30912. }
  30913. if (!this._cachedTextureMatrix) {
  30914. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30915. }
  30916. if (!this._projectionModeMatrix) {
  30917. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30918. }
  30919. this._cachedUOffset = this.uOffset;
  30920. this._cachedVOffset = this.vOffset;
  30921. this._cachedUScale = this.uScale;
  30922. this._cachedVScale = this.vScale;
  30923. this._cachedCoordinatesMode = this.coordinatesMode;
  30924. switch (this.coordinatesMode) {
  30925. case Texture.PLANAR_MODE:
  30926. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30927. this._cachedTextureMatrix[0] = this.uScale;
  30928. this._cachedTextureMatrix[5] = this.vScale;
  30929. this._cachedTextureMatrix[12] = this.uOffset;
  30930. this._cachedTextureMatrix[13] = this.vOffset;
  30931. break;
  30932. case Texture.PROJECTION_MODE:
  30933. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30934. this._projectionModeMatrix.m[0] = 0.5;
  30935. this._projectionModeMatrix.m[5] = -0.5;
  30936. this._projectionModeMatrix.m[10] = 0.0;
  30937. this._projectionModeMatrix.m[12] = 0.5;
  30938. this._projectionModeMatrix.m[13] = 0.5;
  30939. this._projectionModeMatrix.m[14] = 1.0;
  30940. this._projectionModeMatrix.m[15] = 1.0;
  30941. var projectionMatrix = scene.getProjectionMatrix();
  30942. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30943. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30944. break;
  30945. default:
  30946. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30947. break;
  30948. }
  30949. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30950. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30951. });
  30952. return this._cachedTextureMatrix;
  30953. };
  30954. Texture.prototype.clone = function () {
  30955. var _this = this;
  30956. return BABYLON.SerializationHelper.Clone(function () {
  30957. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30958. }, this);
  30959. };
  30960. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30961. get: function () {
  30962. if (!this._onLoadObservable) {
  30963. this._onLoadObservable = new BABYLON.Observable();
  30964. }
  30965. return this._onLoadObservable;
  30966. },
  30967. enumerable: true,
  30968. configurable: true
  30969. });
  30970. Texture.prototype.serialize = function () {
  30971. var serializationObject = _super.prototype.serialize.call(this);
  30972. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30973. serializationObject.base64String = this._buffer;
  30974. serializationObject.name = serializationObject.name.replace("data:", "");
  30975. }
  30976. serializationObject.invertY = this._invertY;
  30977. serializationObject.samplingMode = this.samplingMode;
  30978. return serializationObject;
  30979. };
  30980. Texture.prototype.getClassName = function () {
  30981. return "Texture";
  30982. };
  30983. Texture.prototype.dispose = function () {
  30984. _super.prototype.dispose.call(this);
  30985. if (this.onLoadObservable) {
  30986. this.onLoadObservable.clear();
  30987. this._onLoadObservable = null;
  30988. }
  30989. this._delayedOnLoad = null;
  30990. this._delayedOnError = null;
  30991. };
  30992. // Statics
  30993. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30994. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30995. if (onLoad === void 0) { onLoad = null; }
  30996. if (onError === void 0) { onError = null; }
  30997. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30998. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30999. };
  31000. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31001. if (parsedTexture.customType) {
  31002. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31003. // Update Sampling Mode
  31004. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31005. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31006. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31007. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31008. }
  31009. }
  31010. return parsedCustomTexture;
  31011. }
  31012. if (parsedTexture.isCube) {
  31013. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31014. }
  31015. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31016. return null;
  31017. }
  31018. var texture = BABYLON.SerializationHelper.Parse(function () {
  31019. var generateMipMaps = true;
  31020. if (parsedTexture.noMipmap) {
  31021. generateMipMaps = false;
  31022. }
  31023. if (parsedTexture.mirrorPlane) {
  31024. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31025. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31026. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31027. return mirrorTexture;
  31028. }
  31029. else if (parsedTexture.isRenderTarget) {
  31030. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31031. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31032. return renderTargetTexture;
  31033. }
  31034. else {
  31035. var texture;
  31036. if (parsedTexture.base64String) {
  31037. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31038. }
  31039. else {
  31040. var url = rootUrl + parsedTexture.name;
  31041. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31042. url = parsedTexture.url;
  31043. }
  31044. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31045. }
  31046. return texture;
  31047. }
  31048. }, parsedTexture, scene);
  31049. // Update Sampling Mode
  31050. if (parsedTexture.samplingMode) {
  31051. var sampling = parsedTexture.samplingMode;
  31052. if (texture._samplingMode !== sampling) {
  31053. texture.updateSamplingMode(sampling);
  31054. }
  31055. }
  31056. // Animations
  31057. if (parsedTexture.animations) {
  31058. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31059. var parsedAnimation = parsedTexture.animations[animationIndex];
  31060. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31061. }
  31062. }
  31063. return texture;
  31064. };
  31065. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31066. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31067. if (noMipmap === void 0) { noMipmap = false; }
  31068. if (invertY === void 0) { invertY = true; }
  31069. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31070. if (onLoad === void 0) { onLoad = null; }
  31071. if (onError === void 0) { onError = null; }
  31072. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31073. if (name.substr(0, 5) !== "data:") {
  31074. name = "data:" + name;
  31075. }
  31076. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31077. };
  31078. // Constants
  31079. Texture.NEAREST_SAMPLINGMODE = 1;
  31080. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31081. Texture.BILINEAR_SAMPLINGMODE = 2;
  31082. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31083. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31084. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31085. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31086. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31087. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31088. Texture.NEAREST_LINEAR = 7;
  31089. Texture.NEAREST_NEAREST = 8;
  31090. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31091. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31092. Texture.LINEAR_LINEAR = 11;
  31093. Texture.LINEAR_NEAREST = 12;
  31094. Texture.EXPLICIT_MODE = 0;
  31095. Texture.SPHERICAL_MODE = 1;
  31096. Texture.PLANAR_MODE = 2;
  31097. Texture.CUBIC_MODE = 3;
  31098. Texture.PROJECTION_MODE = 4;
  31099. Texture.SKYBOX_MODE = 5;
  31100. Texture.INVCUBIC_MODE = 6;
  31101. Texture.EQUIRECTANGULAR_MODE = 7;
  31102. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31103. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31104. Texture.CLAMP_ADDRESSMODE = 0;
  31105. Texture.WRAP_ADDRESSMODE = 1;
  31106. Texture.MIRROR_ADDRESSMODE = 2;
  31107. /**
  31108. * 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
  31109. */
  31110. Texture.UseSerializedUrlIfAny = false;
  31111. __decorate([
  31112. BABYLON.serialize()
  31113. ], Texture.prototype, "url", void 0);
  31114. __decorate([
  31115. BABYLON.serialize()
  31116. ], Texture.prototype, "uOffset", void 0);
  31117. __decorate([
  31118. BABYLON.serialize()
  31119. ], Texture.prototype, "vOffset", void 0);
  31120. __decorate([
  31121. BABYLON.serialize()
  31122. ], Texture.prototype, "uScale", void 0);
  31123. __decorate([
  31124. BABYLON.serialize()
  31125. ], Texture.prototype, "vScale", void 0);
  31126. __decorate([
  31127. BABYLON.serialize()
  31128. ], Texture.prototype, "uAng", void 0);
  31129. __decorate([
  31130. BABYLON.serialize()
  31131. ], Texture.prototype, "vAng", void 0);
  31132. __decorate([
  31133. BABYLON.serialize()
  31134. ], Texture.prototype, "wAng", void 0);
  31135. __decorate([
  31136. BABYLON.serialize()
  31137. ], Texture.prototype, "uRotationCenter", void 0);
  31138. __decorate([
  31139. BABYLON.serialize()
  31140. ], Texture.prototype, "vRotationCenter", void 0);
  31141. __decorate([
  31142. BABYLON.serialize()
  31143. ], Texture.prototype, "wRotationCenter", void 0);
  31144. __decorate([
  31145. BABYLON.serialize()
  31146. ], Texture.prototype, "isBlocking", null);
  31147. return Texture;
  31148. }(BABYLON.BaseTexture));
  31149. BABYLON.Texture = Texture;
  31150. })(BABYLON || (BABYLON = {}));
  31151. //# sourceMappingURL=babylon.texture.js.map
  31152. var BABYLON;
  31153. (function (BABYLON) {
  31154. /**
  31155. * @hidden
  31156. **/
  31157. var _InstancesBatch = /** @class */ (function () {
  31158. function _InstancesBatch() {
  31159. this.mustReturn = false;
  31160. this.visibleInstances = new Array();
  31161. this.renderSelf = new Array();
  31162. }
  31163. return _InstancesBatch;
  31164. }());
  31165. BABYLON._InstancesBatch = _InstancesBatch;
  31166. var Mesh = /** @class */ (function (_super) {
  31167. __extends(Mesh, _super);
  31168. /**
  31169. * @constructor
  31170. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31171. * @param {Scene} scene The scene to add this mesh to.
  31172. * @param {Node} parent The parent of this mesh, if it has one
  31173. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31174. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31175. * When false, achieved by calling a clone(), also passing False.
  31176. * This will make creation of children, recursive.
  31177. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31178. */
  31179. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31180. if (scene === void 0) { scene = null; }
  31181. if (parent === void 0) { parent = null; }
  31182. if (source === void 0) { source = null; }
  31183. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31184. var _this = _super.call(this, name, scene) || this;
  31185. // Events
  31186. /**
  31187. * An event triggered before rendering the mesh
  31188. */
  31189. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31190. /**
  31191. * An event triggered after rendering the mesh
  31192. */
  31193. _this.onAfterRenderObservable = new BABYLON.Observable();
  31194. /**
  31195. * An event triggered before drawing the mesh
  31196. */
  31197. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31198. // Members
  31199. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31200. _this.instances = new Array();
  31201. _this._LODLevels = new Array();
  31202. _this._visibleInstances = {};
  31203. _this._renderIdForInstances = new Array();
  31204. _this._batchCache = new _InstancesBatch();
  31205. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31206. // Use by builder only to know what orientation were the mesh build in.
  31207. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31208. _this.overrideMaterialSideOrientation = null;
  31209. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31210. // Will be used to save a source mesh reference, If any
  31211. _this._source = null;
  31212. scene = _this.getScene();
  31213. if (source) {
  31214. // Geometry
  31215. if (source._geometry) {
  31216. source._geometry.applyToMesh(_this);
  31217. }
  31218. // Deep copy
  31219. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31220. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31221. // Source mesh
  31222. _this._source = source;
  31223. // Metadata
  31224. if (source.metadata && source.metadata.clone) {
  31225. _this.metadata = source.metadata.clone();
  31226. }
  31227. else {
  31228. _this.metadata = source.metadata;
  31229. }
  31230. // Tags
  31231. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31232. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31233. }
  31234. // Parent
  31235. _this.parent = source.parent;
  31236. // Pivot
  31237. _this.setPivotMatrix(source.getPivotMatrix());
  31238. _this.id = name + "." + source.id;
  31239. // Material
  31240. _this.material = source.material;
  31241. var index;
  31242. if (!doNotCloneChildren) {
  31243. // Children
  31244. var directDescendants = source.getDescendants(true);
  31245. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31246. var child = directDescendants[index_1];
  31247. if (child.clone) {
  31248. child.clone(name + "." + child.name, _this);
  31249. }
  31250. }
  31251. }
  31252. // Physics clone
  31253. var physicsEngine = _this.getScene().getPhysicsEngine();
  31254. if (clonePhysicsImpostor && physicsEngine) {
  31255. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31256. if (impostor) {
  31257. _this.physicsImpostor = impostor.clone(_this);
  31258. }
  31259. }
  31260. // Particles
  31261. for (index = 0; index < scene.particleSystems.length; index++) {
  31262. var system = scene.particleSystems[index];
  31263. if (system.emitter === source) {
  31264. system.clone(system.name, _this);
  31265. }
  31266. }
  31267. _this.computeWorldMatrix(true);
  31268. }
  31269. // Parent
  31270. if (parent !== null) {
  31271. _this.parent = parent;
  31272. }
  31273. return _this;
  31274. }
  31275. Object.defineProperty(Mesh, "FRONTSIDE", {
  31276. /**
  31277. * Mesh side orientation : usually the external or front surface
  31278. */
  31279. get: function () {
  31280. return Mesh._FRONTSIDE;
  31281. },
  31282. enumerable: true,
  31283. configurable: true
  31284. });
  31285. Object.defineProperty(Mesh, "BACKSIDE", {
  31286. /**
  31287. * Mesh side orientation : usually the internal or back surface
  31288. */
  31289. get: function () {
  31290. return Mesh._BACKSIDE;
  31291. },
  31292. enumerable: true,
  31293. configurable: true
  31294. });
  31295. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31296. /**
  31297. * Mesh side orientation : both internal and external or front and back surfaces
  31298. */
  31299. get: function () {
  31300. return Mesh._DOUBLESIDE;
  31301. },
  31302. enumerable: true,
  31303. configurable: true
  31304. });
  31305. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31306. /**
  31307. * Mesh side orientation : by default, `FRONTSIDE`
  31308. */
  31309. get: function () {
  31310. return Mesh._DEFAULTSIDE;
  31311. },
  31312. enumerable: true,
  31313. configurable: true
  31314. });
  31315. Object.defineProperty(Mesh, "NO_CAP", {
  31316. /**
  31317. * Mesh cap setting : no cap
  31318. */
  31319. get: function () {
  31320. return Mesh._NO_CAP;
  31321. },
  31322. enumerable: true,
  31323. configurable: true
  31324. });
  31325. Object.defineProperty(Mesh, "CAP_START", {
  31326. /**
  31327. * Mesh cap setting : one cap at the beginning of the mesh
  31328. */
  31329. get: function () {
  31330. return Mesh._CAP_START;
  31331. },
  31332. enumerable: true,
  31333. configurable: true
  31334. });
  31335. Object.defineProperty(Mesh, "CAP_END", {
  31336. /**
  31337. * Mesh cap setting : one cap at the end of the mesh
  31338. */
  31339. get: function () {
  31340. return Mesh._CAP_END;
  31341. },
  31342. enumerable: true,
  31343. configurable: true
  31344. });
  31345. Object.defineProperty(Mesh, "CAP_ALL", {
  31346. /**
  31347. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31348. */
  31349. get: function () {
  31350. return Mesh._CAP_ALL;
  31351. },
  31352. enumerable: true,
  31353. configurable: true
  31354. });
  31355. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31356. set: function (callback) {
  31357. if (this._onBeforeDrawObserver) {
  31358. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31359. }
  31360. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31361. },
  31362. enumerable: true,
  31363. configurable: true
  31364. });
  31365. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31366. get: function () {
  31367. return this._morphTargetManager;
  31368. },
  31369. set: function (value) {
  31370. if (this._morphTargetManager === value) {
  31371. return;
  31372. }
  31373. this._morphTargetManager = value;
  31374. this._syncGeometryWithMorphTargetManager();
  31375. },
  31376. enumerable: true,
  31377. configurable: true
  31378. });
  31379. Object.defineProperty(Mesh.prototype, "source", {
  31380. get: function () {
  31381. return this._source;
  31382. },
  31383. enumerable: true,
  31384. configurable: true
  31385. });
  31386. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31387. get: function () {
  31388. return this._unIndexed;
  31389. },
  31390. set: function (value) {
  31391. if (this._unIndexed !== value) {
  31392. this._unIndexed = value;
  31393. this._markSubMeshesAsAttributesDirty();
  31394. }
  31395. },
  31396. enumerable: true,
  31397. configurable: true
  31398. });
  31399. // Methods
  31400. /**
  31401. * Returns the string "Mesh".
  31402. */
  31403. Mesh.prototype.getClassName = function () {
  31404. return "Mesh";
  31405. };
  31406. /**
  31407. * Returns a string.
  31408. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31409. */
  31410. Mesh.prototype.toString = function (fullDetails) {
  31411. var ret = _super.prototype.toString.call(this, fullDetails);
  31412. ret += ", n vertices: " + this.getTotalVertices();
  31413. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31414. if (this.animations) {
  31415. for (var i = 0; i < this.animations.length; i++) {
  31416. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31417. }
  31418. }
  31419. if (fullDetails) {
  31420. if (this._geometry) {
  31421. var ib = this.getIndices();
  31422. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31423. if (vb && ib) {
  31424. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31425. }
  31426. }
  31427. else {
  31428. ret += ", flat shading: UNKNOWN";
  31429. }
  31430. }
  31431. return ret;
  31432. };
  31433. Mesh.prototype._unBindEffect = function () {
  31434. _super.prototype._unBindEffect.call(this);
  31435. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31436. var instance = _a[_i];
  31437. instance._unBindEffect();
  31438. }
  31439. };
  31440. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31441. /**
  31442. * True if the mesh has some Levels Of Details (LOD).
  31443. * Returns a boolean.
  31444. */
  31445. get: function () {
  31446. return this._LODLevels.length > 0;
  31447. },
  31448. enumerable: true,
  31449. configurable: true
  31450. });
  31451. /**
  31452. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31453. * @returns an array of {BABYLON.MeshLODLevel}
  31454. */
  31455. Mesh.prototype.getLODLevels = function () {
  31456. return this._LODLevels;
  31457. };
  31458. Mesh.prototype._sortLODLevels = function () {
  31459. this._LODLevels.sort(function (a, b) {
  31460. if (a.distance < b.distance) {
  31461. return 1;
  31462. }
  31463. if (a.distance > b.distance) {
  31464. return -1;
  31465. }
  31466. return 0;
  31467. });
  31468. };
  31469. /**
  31470. * Add a mesh as LOD level triggered at the given distance.
  31471. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31472. * @param {number} distance The distance from the center of the object to show this level
  31473. * @param {Mesh} mesh The mesh to be added as LOD level
  31474. * @return {Mesh} This mesh (for chaining)
  31475. */
  31476. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31477. if (mesh && mesh._masterMesh) {
  31478. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31479. return this;
  31480. }
  31481. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31482. this._LODLevels.push(level);
  31483. if (mesh) {
  31484. mesh._masterMesh = this;
  31485. }
  31486. this._sortLODLevels();
  31487. return this;
  31488. };
  31489. /**
  31490. * Returns the LOD level mesh at the passed distance or null if not found.
  31491. * It is related to the method `addLODLevel(distance, mesh)`.
  31492. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31493. * Returns an object Mesh or `null`.
  31494. */
  31495. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31496. for (var index = 0; index < this._LODLevels.length; index++) {
  31497. var level = this._LODLevels[index];
  31498. if (level.distance === distance) {
  31499. return level.mesh;
  31500. }
  31501. }
  31502. return null;
  31503. };
  31504. /**
  31505. * Remove a mesh from the LOD array
  31506. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31507. * @param {Mesh} mesh The mesh to be removed.
  31508. * @return {Mesh} This mesh (for chaining)
  31509. */
  31510. Mesh.prototype.removeLODLevel = function (mesh) {
  31511. for (var index = 0; index < this._LODLevels.length; index++) {
  31512. if (this._LODLevels[index].mesh === mesh) {
  31513. this._LODLevels.splice(index, 1);
  31514. if (mesh) {
  31515. mesh._masterMesh = null;
  31516. }
  31517. }
  31518. }
  31519. this._sortLODLevels();
  31520. return this;
  31521. };
  31522. /**
  31523. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31524. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31525. */
  31526. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31527. if (!this._LODLevels || this._LODLevels.length === 0) {
  31528. return this;
  31529. }
  31530. var bSphere;
  31531. if (boundingSphere) {
  31532. bSphere = boundingSphere;
  31533. }
  31534. else {
  31535. var boundingInfo = this.getBoundingInfo();
  31536. bSphere = boundingInfo.boundingSphere;
  31537. }
  31538. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31539. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31540. if (this.onLODLevelSelection) {
  31541. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31542. }
  31543. return this;
  31544. }
  31545. for (var index = 0; index < this._LODLevels.length; index++) {
  31546. var level = this._LODLevels[index];
  31547. if (level.distance < distanceToCamera) {
  31548. if (level.mesh) {
  31549. level.mesh._preActivate();
  31550. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31551. }
  31552. if (this.onLODLevelSelection) {
  31553. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31554. }
  31555. return level.mesh;
  31556. }
  31557. }
  31558. if (this.onLODLevelSelection) {
  31559. this.onLODLevelSelection(distanceToCamera, this, this);
  31560. }
  31561. return this;
  31562. };
  31563. Object.defineProperty(Mesh.prototype, "geometry", {
  31564. /**
  31565. * Returns the mesh internal Geometry object.
  31566. */
  31567. get: function () {
  31568. return this._geometry;
  31569. },
  31570. enumerable: true,
  31571. configurable: true
  31572. });
  31573. /**
  31574. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31575. */
  31576. Mesh.prototype.getTotalVertices = function () {
  31577. if (this._geometry === null || this._geometry === undefined) {
  31578. return 0;
  31579. }
  31580. return this._geometry.getTotalVertices();
  31581. };
  31582. /**
  31583. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31584. * 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.
  31585. * You can force the copy with forceCopy === true
  31586. * Returns null if the mesh has no geometry or no vertex buffer.
  31587. * Possible `kind` values :
  31588. * - BABYLON.VertexBuffer.PositionKind
  31589. * - BABYLON.VertexBuffer.UVKind
  31590. * - BABYLON.VertexBuffer.UV2Kind
  31591. * - BABYLON.VertexBuffer.UV3Kind
  31592. * - BABYLON.VertexBuffer.UV4Kind
  31593. * - BABYLON.VertexBuffer.UV5Kind
  31594. * - BABYLON.VertexBuffer.UV6Kind
  31595. * - BABYLON.VertexBuffer.ColorKind
  31596. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31597. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31598. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31599. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31600. */
  31601. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31602. if (!this._geometry) {
  31603. return null;
  31604. }
  31605. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31606. };
  31607. /**
  31608. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31609. * Returns `null` if the mesh has no geometry.
  31610. * Possible `kind` values :
  31611. * - BABYLON.VertexBuffer.PositionKind
  31612. * - BABYLON.VertexBuffer.UVKind
  31613. * - BABYLON.VertexBuffer.UV2Kind
  31614. * - BABYLON.VertexBuffer.UV3Kind
  31615. * - BABYLON.VertexBuffer.UV4Kind
  31616. * - BABYLON.VertexBuffer.UV5Kind
  31617. * - BABYLON.VertexBuffer.UV6Kind
  31618. * - BABYLON.VertexBuffer.ColorKind
  31619. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31620. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31621. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31622. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31623. */
  31624. Mesh.prototype.getVertexBuffer = function (kind) {
  31625. if (!this._geometry) {
  31626. return null;
  31627. }
  31628. return this._geometry.getVertexBuffer(kind);
  31629. };
  31630. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31631. if (!this._geometry) {
  31632. if (this._delayInfo) {
  31633. return this._delayInfo.indexOf(kind) !== -1;
  31634. }
  31635. return false;
  31636. }
  31637. return this._geometry.isVerticesDataPresent(kind);
  31638. };
  31639. /**
  31640. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31641. * Possible `kind` values :
  31642. * - BABYLON.VertexBuffer.PositionKind
  31643. * - BABYLON.VertexBuffer.UVKind
  31644. * - BABYLON.VertexBuffer.UV2Kind
  31645. * - BABYLON.VertexBuffer.UV3Kind
  31646. * - BABYLON.VertexBuffer.UV4Kind
  31647. * - BABYLON.VertexBuffer.UV5Kind
  31648. * - BABYLON.VertexBuffer.UV6Kind
  31649. * - BABYLON.VertexBuffer.ColorKind
  31650. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31651. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31652. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31653. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31654. */
  31655. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31656. if (!this._geometry) {
  31657. if (this._delayInfo) {
  31658. return this._delayInfo.indexOf(kind) !== -1;
  31659. }
  31660. return false;
  31661. }
  31662. return this._geometry.isVertexBufferUpdatable(kind);
  31663. };
  31664. /**
  31665. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31666. * Possible `kind` values :
  31667. * - BABYLON.VertexBuffer.PositionKind
  31668. * - BABYLON.VertexBuffer.UVKind
  31669. * - BABYLON.VertexBuffer.UV2Kind
  31670. * - BABYLON.VertexBuffer.UV3Kind
  31671. * - BABYLON.VertexBuffer.UV4Kind
  31672. * - BABYLON.VertexBuffer.UV5Kind
  31673. * - BABYLON.VertexBuffer.UV6Kind
  31674. * - BABYLON.VertexBuffer.ColorKind
  31675. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31676. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31677. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31678. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31679. */
  31680. Mesh.prototype.getVerticesDataKinds = function () {
  31681. if (!this._geometry) {
  31682. var result = new Array();
  31683. if (this._delayInfo) {
  31684. this._delayInfo.forEach(function (kind, index, array) {
  31685. result.push(kind);
  31686. });
  31687. }
  31688. return result;
  31689. }
  31690. return this._geometry.getVerticesDataKinds();
  31691. };
  31692. /**
  31693. * Returns a positive integer : the total number of indices in this mesh geometry.
  31694. * Returns zero if the mesh has no geometry.
  31695. */
  31696. Mesh.prototype.getTotalIndices = function () {
  31697. if (!this._geometry) {
  31698. return 0;
  31699. }
  31700. return this._geometry.getTotalIndices();
  31701. };
  31702. /**
  31703. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31704. * 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.
  31705. * Returns an empty array if the mesh has no geometry.
  31706. */
  31707. Mesh.prototype.getIndices = function (copyWhenShared) {
  31708. if (!this._geometry) {
  31709. return [];
  31710. }
  31711. return this._geometry.getIndices(copyWhenShared);
  31712. };
  31713. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31714. get: function () {
  31715. return this._masterMesh !== null && this._masterMesh !== undefined;
  31716. },
  31717. enumerable: true,
  31718. configurable: true
  31719. });
  31720. /**
  31721. * Determine if the current mesh is ready to be rendered
  31722. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31723. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31724. * @returns true if all associated assets are ready (material, textures, shaders)
  31725. */
  31726. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31727. if (completeCheck === void 0) { completeCheck = false; }
  31728. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31729. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31730. return false;
  31731. }
  31732. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31733. return false;
  31734. }
  31735. if (!this.subMeshes || this.subMeshes.length === 0) {
  31736. return true;
  31737. }
  31738. if (!completeCheck) {
  31739. return true;
  31740. }
  31741. var engine = this.getEngine();
  31742. var scene = this.getScene();
  31743. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31744. this.computeWorldMatrix();
  31745. var mat = this.material || scene.defaultMaterial;
  31746. if (mat) {
  31747. if (mat.storeEffectOnSubMeshes) {
  31748. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31749. var subMesh = _a[_i];
  31750. var effectiveMaterial = subMesh.getMaterial();
  31751. if (effectiveMaterial) {
  31752. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31753. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31754. return false;
  31755. }
  31756. }
  31757. else {
  31758. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31759. return false;
  31760. }
  31761. }
  31762. }
  31763. }
  31764. }
  31765. else {
  31766. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31767. return false;
  31768. }
  31769. }
  31770. }
  31771. // Shadows
  31772. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31773. var light = _c[_b];
  31774. var generator = light.getShadowGenerator();
  31775. if (generator) {
  31776. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31777. var subMesh = _e[_d];
  31778. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31779. return false;
  31780. }
  31781. }
  31782. }
  31783. }
  31784. // LOD
  31785. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31786. var lod = _g[_f];
  31787. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31788. return false;
  31789. }
  31790. }
  31791. return true;
  31792. };
  31793. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31794. /**
  31795. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31796. * This property is pertinent only for updatable parametric shapes.
  31797. */
  31798. get: function () {
  31799. return this._areNormalsFrozen;
  31800. },
  31801. enumerable: true,
  31802. configurable: true
  31803. });
  31804. /**
  31805. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31806. * It has no effect at all on other shapes.
  31807. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31808. * Returns the Mesh.
  31809. */
  31810. Mesh.prototype.freezeNormals = function () {
  31811. this._areNormalsFrozen = true;
  31812. return this;
  31813. };
  31814. /**
  31815. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31816. * It has no effect at all on other shapes.
  31817. * It reactivates the mesh normals computation if it was previously frozen.
  31818. * Returns the Mesh.
  31819. */
  31820. Mesh.prototype.unfreezeNormals = function () {
  31821. this._areNormalsFrozen = false;
  31822. return this;
  31823. };
  31824. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31825. /**
  31826. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31827. */
  31828. set: function (count) {
  31829. this._overridenInstanceCount = count;
  31830. },
  31831. enumerable: true,
  31832. configurable: true
  31833. });
  31834. // Methods
  31835. Mesh.prototype._preActivate = function () {
  31836. var sceneRenderId = this.getScene().getRenderId();
  31837. if (this._preActivateId === sceneRenderId) {
  31838. return this;
  31839. }
  31840. this._preActivateId = sceneRenderId;
  31841. this._visibleInstances = null;
  31842. return this;
  31843. };
  31844. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31845. if (this._visibleInstances) {
  31846. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31847. }
  31848. return this;
  31849. };
  31850. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31851. if (!this._visibleInstances) {
  31852. this._visibleInstances = {};
  31853. this._visibleInstances.defaultRenderId = renderId;
  31854. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31855. }
  31856. if (!this._visibleInstances[renderId]) {
  31857. this._visibleInstances[renderId] = new Array();
  31858. }
  31859. this._visibleInstances[renderId].push(instance);
  31860. return this;
  31861. };
  31862. /**
  31863. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31864. * This means the mesh underlying bounding box and sphere are recomputed.
  31865. * Returns the Mesh.
  31866. */
  31867. Mesh.prototype.refreshBoundingInfo = function () {
  31868. return this._refreshBoundingInfo(false);
  31869. };
  31870. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31871. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31872. return this;
  31873. }
  31874. var data = this._getPositionData(applySkeleton);
  31875. if (data) {
  31876. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31877. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31878. }
  31879. if (this.subMeshes) {
  31880. for (var index = 0; index < this.subMeshes.length; index++) {
  31881. this.subMeshes[index].refreshBoundingInfo();
  31882. }
  31883. }
  31884. this._updateBoundingInfo();
  31885. return this;
  31886. };
  31887. Mesh.prototype._getPositionData = function (applySkeleton) {
  31888. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31889. if (data && applySkeleton && this.skeleton) {
  31890. data = BABYLON.Tools.Slice(data);
  31891. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31892. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31893. if (matricesWeightsData && matricesIndicesData) {
  31894. var needExtras = this.numBoneInfluencers > 4;
  31895. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31896. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31897. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31898. var tempVector = BABYLON.Tmp.Vector3[0];
  31899. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31900. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31901. var matWeightIdx = 0;
  31902. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31903. finalMatrix.reset();
  31904. var inf;
  31905. var weight;
  31906. for (inf = 0; inf < 4; inf++) {
  31907. weight = matricesWeightsData[matWeightIdx + inf];
  31908. if (weight <= 0)
  31909. break;
  31910. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31911. finalMatrix.addToSelf(tempMatrix);
  31912. }
  31913. if (needExtras) {
  31914. for (inf = 0; inf < 4; inf++) {
  31915. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31916. if (weight <= 0)
  31917. break;
  31918. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31919. finalMatrix.addToSelf(tempMatrix);
  31920. }
  31921. }
  31922. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31923. tempVector.toArray(data, index);
  31924. }
  31925. }
  31926. }
  31927. return data;
  31928. };
  31929. Mesh.prototype._createGlobalSubMesh = function (force) {
  31930. var totalVertices = this.getTotalVertices();
  31931. if (!totalVertices || !this.getIndices()) {
  31932. return null;
  31933. }
  31934. // Check if we need to recreate the submeshes
  31935. if (this.subMeshes && this.subMeshes.length > 0) {
  31936. var ib = this.getIndices();
  31937. if (!ib) {
  31938. return null;
  31939. }
  31940. var totalIndices = ib.length;
  31941. var needToRecreate = false;
  31942. if (force) {
  31943. needToRecreate = true;
  31944. }
  31945. else {
  31946. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31947. var submesh = _a[_i];
  31948. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31949. needToRecreate = true;
  31950. break;
  31951. }
  31952. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31953. needToRecreate = true;
  31954. break;
  31955. }
  31956. }
  31957. }
  31958. if (!needToRecreate) {
  31959. return this.subMeshes[0];
  31960. }
  31961. }
  31962. this.releaseSubMeshes();
  31963. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31964. };
  31965. Mesh.prototype.subdivide = function (count) {
  31966. if (count < 1) {
  31967. return;
  31968. }
  31969. var totalIndices = this.getTotalIndices();
  31970. var subdivisionSize = (totalIndices / count) | 0;
  31971. var offset = 0;
  31972. // Ensure that subdivisionSize is a multiple of 3
  31973. while (subdivisionSize % 3 !== 0) {
  31974. subdivisionSize++;
  31975. }
  31976. this.releaseSubMeshes();
  31977. for (var index = 0; index < count; index++) {
  31978. if (offset >= totalIndices) {
  31979. break;
  31980. }
  31981. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31982. offset += subdivisionSize;
  31983. }
  31984. this.synchronizeInstances();
  31985. };
  31986. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31987. if (updatable === void 0) { updatable = false; }
  31988. if (!this._geometry) {
  31989. var vertexData = new BABYLON.VertexData();
  31990. vertexData.set(data, kind);
  31991. var scene = this.getScene();
  31992. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31993. }
  31994. else {
  31995. this._geometry.setVerticesData(kind, data, updatable, stride);
  31996. }
  31997. return this;
  31998. };
  31999. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32000. if (updatable === void 0) { updatable = true; }
  32001. var vb = this.getVertexBuffer(kind);
  32002. if (!vb || vb.isUpdatable() === updatable) {
  32003. return;
  32004. }
  32005. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32006. };
  32007. /**
  32008. * Sets the mesh VertexBuffer.
  32009. * Returns the Mesh.
  32010. */
  32011. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32012. if (!this._geometry) {
  32013. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32014. }
  32015. this._geometry.setVerticesBuffer(buffer);
  32016. return this;
  32017. };
  32018. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32019. if (!this._geometry) {
  32020. return this;
  32021. }
  32022. if (!makeItUnique) {
  32023. this._geometry.updateVerticesData(kind, data, updateExtends);
  32024. }
  32025. else {
  32026. this.makeGeometryUnique();
  32027. this.updateVerticesData(kind, data, updateExtends, false);
  32028. }
  32029. return this;
  32030. };
  32031. /**
  32032. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32033. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32034. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32035. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32036. * Returns the Mesh.
  32037. */
  32038. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32039. if (computeNormals === void 0) { computeNormals = true; }
  32040. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32041. if (!positions) {
  32042. return this;
  32043. }
  32044. positionFunction(positions);
  32045. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32046. if (computeNormals) {
  32047. var indices = this.getIndices();
  32048. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32049. if (!normals) {
  32050. return this;
  32051. }
  32052. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32053. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32054. }
  32055. return this;
  32056. };
  32057. /**
  32058. * Creates a un-shared specific occurence of the geometry for the mesh.
  32059. * Returns the Mesh.
  32060. */
  32061. Mesh.prototype.makeGeometryUnique = function () {
  32062. if (!this._geometry) {
  32063. return this;
  32064. }
  32065. var oldGeometry = this._geometry;
  32066. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32067. oldGeometry.releaseForMesh(this, true);
  32068. geometry.applyToMesh(this);
  32069. return this;
  32070. };
  32071. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32072. if (totalVertices === void 0) { totalVertices = null; }
  32073. if (updatable === void 0) { updatable = false; }
  32074. if (!this._geometry) {
  32075. var vertexData = new BABYLON.VertexData();
  32076. vertexData.indices = indices;
  32077. var scene = this.getScene();
  32078. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32079. }
  32080. else {
  32081. this._geometry.setIndices(indices, totalVertices, updatable);
  32082. }
  32083. return this;
  32084. };
  32085. /**
  32086. * Update the current index buffer
  32087. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32088. * Returns the Mesh.
  32089. */
  32090. Mesh.prototype.updateIndices = function (indices, offset) {
  32091. if (!this._geometry) {
  32092. return this;
  32093. }
  32094. this._geometry.updateIndices(indices, offset);
  32095. return this;
  32096. };
  32097. /**
  32098. * Invert the geometry to move from a right handed system to a left handed one.
  32099. * Returns the Mesh.
  32100. */
  32101. Mesh.prototype.toLeftHanded = function () {
  32102. if (!this._geometry) {
  32103. return this;
  32104. }
  32105. this._geometry.toLeftHanded();
  32106. return this;
  32107. };
  32108. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32109. if (!this._geometry) {
  32110. return this;
  32111. }
  32112. var engine = this.getScene().getEngine();
  32113. // Wireframe
  32114. var indexToBind;
  32115. if (this._unIndexed) {
  32116. indexToBind = null;
  32117. }
  32118. else {
  32119. switch (fillMode) {
  32120. case BABYLON.Material.PointFillMode:
  32121. indexToBind = null;
  32122. break;
  32123. case BABYLON.Material.WireFrameFillMode:
  32124. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32125. break;
  32126. default:
  32127. case BABYLON.Material.TriangleFillMode:
  32128. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32129. break;
  32130. }
  32131. }
  32132. // VBOs
  32133. this._geometry._bind(effect, indexToBind);
  32134. return this;
  32135. };
  32136. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32137. if (alternate === void 0) { alternate = false; }
  32138. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32139. return this;
  32140. }
  32141. this.onBeforeDrawObservable.notifyObservers(this);
  32142. var scene = this.getScene();
  32143. var engine = scene.getEngine();
  32144. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32145. // or triangles as points
  32146. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32147. }
  32148. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32149. // Triangles as wireframe
  32150. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32151. }
  32152. else {
  32153. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32154. }
  32155. if (scene._isAlternateRenderingEnabled && !alternate) {
  32156. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32157. if (!effect || !scene.activeCamera) {
  32158. return this;
  32159. }
  32160. scene._switchToAlternateCameraConfiguration(true);
  32161. this._effectiveMaterial.bindView(effect);
  32162. this._effectiveMaterial.bindViewProjection(effect);
  32163. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32164. this._draw(subMesh, fillMode, instancesCount, true);
  32165. engine.setViewport(scene.activeCamera.viewport);
  32166. scene._switchToAlternateCameraConfiguration(false);
  32167. this._effectiveMaterial.bindView(effect);
  32168. this._effectiveMaterial.bindViewProjection(effect);
  32169. }
  32170. return this;
  32171. };
  32172. /**
  32173. * Registers for this mesh a javascript function called just before the rendering process.
  32174. * This function is passed the current mesh.
  32175. * Return the Mesh.
  32176. */
  32177. Mesh.prototype.registerBeforeRender = function (func) {
  32178. this.onBeforeRenderObservable.add(func);
  32179. return this;
  32180. };
  32181. /**
  32182. * Disposes a previously registered javascript function called before the rendering.
  32183. * This function is passed the current mesh.
  32184. * Returns the Mesh.
  32185. */
  32186. Mesh.prototype.unregisterBeforeRender = function (func) {
  32187. this.onBeforeRenderObservable.removeCallback(func);
  32188. return this;
  32189. };
  32190. /**
  32191. * Registers for this mesh a javascript function called just after the rendering is complete.
  32192. * This function is passed the current mesh.
  32193. * Returns the Mesh.
  32194. */
  32195. Mesh.prototype.registerAfterRender = function (func) {
  32196. this.onAfterRenderObservable.add(func);
  32197. return this;
  32198. };
  32199. /**
  32200. * Disposes a previously registered javascript function called after the rendering.
  32201. * This function is passed the current mesh.
  32202. * Return the Mesh.
  32203. */
  32204. Mesh.prototype.unregisterAfterRender = function (func) {
  32205. this.onAfterRenderObservable.removeCallback(func);
  32206. return this;
  32207. };
  32208. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32209. var scene = this.getScene();
  32210. this._batchCache.mustReturn = false;
  32211. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32212. this._batchCache.visibleInstances[subMeshId] = null;
  32213. if (this._visibleInstances) {
  32214. var currentRenderId = scene.getRenderId();
  32215. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32216. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32217. var selfRenderId = this._renderId;
  32218. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32219. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32220. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32221. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32222. }
  32223. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32224. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32225. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32226. this._batchCache.mustReturn = true;
  32227. return this._batchCache;
  32228. }
  32229. if (currentRenderId !== selfRenderId) {
  32230. this._batchCache.renderSelf[subMeshId] = false;
  32231. }
  32232. }
  32233. this._renderIdForInstances[subMeshId] = currentRenderId;
  32234. }
  32235. return this._batchCache;
  32236. };
  32237. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32238. var visibleInstances = batch.visibleInstances[subMesh._id];
  32239. if (!visibleInstances) {
  32240. return this;
  32241. }
  32242. var matricesCount = visibleInstances.length + 1;
  32243. var bufferSize = matricesCount * 16 * 4;
  32244. var currentInstancesBufferSize = this._instancesBufferSize;
  32245. var instancesBuffer = this._instancesBuffer;
  32246. while (this._instancesBufferSize < bufferSize) {
  32247. this._instancesBufferSize *= 2;
  32248. }
  32249. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32250. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32251. }
  32252. var offset = 0;
  32253. var instancesCount = 0;
  32254. var world = this.getWorldMatrix();
  32255. if (batch.renderSelf[subMesh._id]) {
  32256. world.copyToArray(this._instancesData, offset);
  32257. offset += 16;
  32258. instancesCount++;
  32259. }
  32260. if (visibleInstances) {
  32261. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32262. var instance = visibleInstances[instanceIndex];
  32263. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32264. offset += 16;
  32265. instancesCount++;
  32266. }
  32267. }
  32268. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32269. if (instancesBuffer) {
  32270. instancesBuffer.dispose();
  32271. }
  32272. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32273. this._instancesBuffer = instancesBuffer;
  32274. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32275. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32276. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32277. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32278. }
  32279. else {
  32280. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32281. }
  32282. this._bind(subMesh, effect, fillMode);
  32283. this._draw(subMesh, fillMode, instancesCount);
  32284. engine.unbindInstanceAttributes();
  32285. return this;
  32286. };
  32287. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32288. var scene = this.getScene();
  32289. var engine = scene.getEngine();
  32290. if (hardwareInstancedRendering) {
  32291. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32292. }
  32293. else {
  32294. if (batch.renderSelf[subMesh._id]) {
  32295. // Draw
  32296. if (onBeforeDraw) {
  32297. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32298. }
  32299. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32300. }
  32301. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32302. if (visibleInstancesForSubMesh) {
  32303. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32304. var instance = visibleInstancesForSubMesh[instanceIndex];
  32305. // World
  32306. var world = instance.getWorldMatrix();
  32307. if (onBeforeDraw) {
  32308. onBeforeDraw(true, world, effectiveMaterial);
  32309. }
  32310. // Draw
  32311. this._draw(subMesh, fillMode);
  32312. }
  32313. }
  32314. }
  32315. return this;
  32316. };
  32317. /**
  32318. * Triggers the draw call for the mesh.
  32319. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32320. * Returns the Mesh.
  32321. */
  32322. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32323. this._checkOcclusionQuery();
  32324. if (this._isOccluded) {
  32325. return this;
  32326. }
  32327. var scene = this.getScene();
  32328. // Managing instances
  32329. var batch = this._getInstancesRenderList(subMesh._id);
  32330. if (batch.mustReturn) {
  32331. return this;
  32332. }
  32333. // Checking geometry state
  32334. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32335. return this;
  32336. }
  32337. this.onBeforeRenderObservable.notifyObservers(this);
  32338. var engine = scene.getEngine();
  32339. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32340. // Material
  32341. var material = subMesh.getMaterial();
  32342. if (!material) {
  32343. return this;
  32344. }
  32345. this._effectiveMaterial = material;
  32346. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32347. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32348. return this;
  32349. }
  32350. }
  32351. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32352. return this;
  32353. }
  32354. // Alpha mode
  32355. if (enableAlphaMode) {
  32356. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32357. }
  32358. // Outline - step 1
  32359. var savedDepthWrite = engine.getDepthWrite();
  32360. if (this.renderOutline) {
  32361. engine.setDepthWrite(false);
  32362. scene.getOutlineRenderer().render(subMesh, batch);
  32363. engine.setDepthWrite(savedDepthWrite);
  32364. }
  32365. var effect;
  32366. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32367. effect = subMesh.effect;
  32368. }
  32369. else {
  32370. effect = this._effectiveMaterial.getEffect();
  32371. }
  32372. if (!effect) {
  32373. return this;
  32374. }
  32375. var sideOrientation = this.overrideMaterialSideOrientation;
  32376. if (sideOrientation == null) {
  32377. sideOrientation = this._effectiveMaterial.sideOrientation;
  32378. if (this._getWorldMatrixDeterminant() < 0) {
  32379. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32380. }
  32381. }
  32382. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32383. if (this._effectiveMaterial.forceDepthWrite) {
  32384. engine.setDepthWrite(true);
  32385. }
  32386. // Bind
  32387. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32388. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32389. this._bind(subMesh, effect, fillMode);
  32390. }
  32391. var world = this.getWorldMatrix();
  32392. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32393. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32394. }
  32395. else {
  32396. this._effectiveMaterial.bind(world, this);
  32397. }
  32398. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32399. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32400. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32401. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32402. }
  32403. // Draw
  32404. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32405. // Unbind
  32406. this._effectiveMaterial.unbind();
  32407. // Outline - step 2
  32408. if (this.renderOutline && savedDepthWrite) {
  32409. engine.setDepthWrite(true);
  32410. engine.setColorWrite(false);
  32411. scene.getOutlineRenderer().render(subMesh, batch);
  32412. engine.setColorWrite(true);
  32413. }
  32414. // Overlay
  32415. if (this.renderOverlay) {
  32416. var currentMode = engine.getAlphaMode();
  32417. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32418. scene.getOutlineRenderer().render(subMesh, batch, true);
  32419. engine.setAlphaMode(currentMode);
  32420. }
  32421. this.onAfterRenderObservable.notifyObservers(this);
  32422. return this;
  32423. };
  32424. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32425. if (isInstance && effectiveMaterial) {
  32426. effectiveMaterial.bindOnlyWorldMatrix(world);
  32427. }
  32428. };
  32429. /**
  32430. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32431. */
  32432. Mesh.prototype.getEmittedParticleSystems = function () {
  32433. var results = new Array();
  32434. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32435. var particleSystem = this.getScene().particleSystems[index];
  32436. if (particleSystem.emitter === this) {
  32437. results.push(particleSystem);
  32438. }
  32439. }
  32440. return results;
  32441. };
  32442. /**
  32443. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32444. */
  32445. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32446. var results = new Array();
  32447. var descendants = this.getDescendants();
  32448. descendants.push(this);
  32449. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32450. var particleSystem = this.getScene().particleSystems[index];
  32451. var emitter = particleSystem.emitter;
  32452. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32453. results.push(particleSystem);
  32454. }
  32455. }
  32456. return results;
  32457. };
  32458. /**
  32459. * Normalize matrix weights so that all vertices have a total weight set to 1
  32460. */
  32461. Mesh.prototype.cleanMatrixWeights = function () {
  32462. var epsilon = 1e-3;
  32463. var noInfluenceBoneIndex = 0.0;
  32464. if (this.skeleton) {
  32465. noInfluenceBoneIndex = this.skeleton.bones.length;
  32466. }
  32467. else {
  32468. return;
  32469. }
  32470. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32471. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32472. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32473. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32474. var influencers = this.numBoneInfluencers;
  32475. var size = matricesWeights.length;
  32476. for (var i = 0; i < size; i += 4) {
  32477. var weight = 0.0;
  32478. var firstZeroWeight = -1;
  32479. for (var j = 0; j < 4; j++) {
  32480. var w = matricesWeights[i + j];
  32481. weight += w;
  32482. if (w < epsilon && firstZeroWeight < 0) {
  32483. firstZeroWeight = j;
  32484. }
  32485. }
  32486. if (matricesWeightsExtra) {
  32487. for (var j = 0; j < 4; j++) {
  32488. var w = matricesWeightsExtra[i + j];
  32489. weight += w;
  32490. if (w < epsilon && firstZeroWeight < 0) {
  32491. firstZeroWeight = j + 4;
  32492. }
  32493. }
  32494. }
  32495. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32496. firstZeroWeight = influencers - 1;
  32497. }
  32498. if (weight > epsilon) {
  32499. var mweight = 1.0 / weight;
  32500. for (var j = 0; j < 4; j++) {
  32501. matricesWeights[i + j] *= mweight;
  32502. }
  32503. if (matricesWeightsExtra) {
  32504. for (var j = 0; j < 4; j++) {
  32505. matricesWeightsExtra[i + j] *= mweight;
  32506. }
  32507. }
  32508. }
  32509. else {
  32510. if (firstZeroWeight >= 4) {
  32511. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32512. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32513. }
  32514. else {
  32515. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32516. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32517. }
  32518. }
  32519. }
  32520. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32521. if (matricesIndicesExtra) {
  32522. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32523. }
  32524. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32525. if (matricesWeightsExtra) {
  32526. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32527. }
  32528. };
  32529. Mesh.prototype._checkDelayState = function () {
  32530. var scene = this.getScene();
  32531. if (this._geometry) {
  32532. this._geometry.load(scene);
  32533. }
  32534. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32535. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32536. this._queueLoad(scene);
  32537. }
  32538. return this;
  32539. };
  32540. Mesh.prototype._queueLoad = function (scene) {
  32541. var _this = this;
  32542. scene._addPendingData(this);
  32543. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32544. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32545. if (data instanceof ArrayBuffer) {
  32546. _this._delayLoadingFunction(data, _this);
  32547. }
  32548. else {
  32549. _this._delayLoadingFunction(JSON.parse(data), _this);
  32550. }
  32551. _this.instances.forEach(function (instance) {
  32552. instance._syncSubMeshes();
  32553. });
  32554. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32555. scene._removePendingData(_this);
  32556. }, function () { }, scene.database, getBinaryData);
  32557. return this;
  32558. };
  32559. /**
  32560. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32561. */
  32562. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32563. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32564. return false;
  32565. }
  32566. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32567. return false;
  32568. }
  32569. this._checkDelayState();
  32570. return true;
  32571. };
  32572. /**
  32573. * Sets the mesh material by the material or multiMaterial `id` property.
  32574. * The material `id` is a string identifying the material or the multiMaterial.
  32575. * This method returns the Mesh.
  32576. */
  32577. Mesh.prototype.setMaterialByID = function (id) {
  32578. var materials = this.getScene().materials;
  32579. var index;
  32580. for (index = materials.length - 1; index > -1; index--) {
  32581. if (materials[index].id === id) {
  32582. this.material = materials[index];
  32583. return this;
  32584. }
  32585. }
  32586. // Multi
  32587. var multiMaterials = this.getScene().multiMaterials;
  32588. for (index = multiMaterials.length - 1; index > -1; index--) {
  32589. if (multiMaterials[index].id === id) {
  32590. this.material = multiMaterials[index];
  32591. return this;
  32592. }
  32593. }
  32594. return this;
  32595. };
  32596. /**
  32597. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32598. */
  32599. Mesh.prototype.getAnimatables = function () {
  32600. var results = new Array();
  32601. if (this.material) {
  32602. results.push(this.material);
  32603. }
  32604. if (this.skeleton) {
  32605. results.push(this.skeleton);
  32606. }
  32607. return results;
  32608. };
  32609. /**
  32610. * Modifies the mesh geometry according to the passed transformation matrix.
  32611. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32612. * The mesh normals are modified accordingly the same transformation.
  32613. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32614. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32615. * Returns the Mesh.
  32616. */
  32617. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32618. // Position
  32619. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32620. return this;
  32621. }
  32622. var submeshes = this.subMeshes.splice(0);
  32623. this._resetPointsArrayCache();
  32624. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32625. var temp = new Array();
  32626. var index;
  32627. for (index = 0; index < data.length; index += 3) {
  32628. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32629. }
  32630. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32631. // Normals
  32632. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32633. return this;
  32634. }
  32635. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32636. temp = [];
  32637. for (index = 0; index < data.length; index += 3) {
  32638. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32639. }
  32640. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32641. // flip faces?
  32642. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32643. this.flipFaces();
  32644. }
  32645. // Restore submeshes
  32646. this.releaseSubMeshes();
  32647. this.subMeshes = submeshes;
  32648. return this;
  32649. };
  32650. /**
  32651. * Modifies the mesh geometry according to its own current World Matrix.
  32652. * The mesh World Matrix is then reset.
  32653. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32654. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32655. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32656. * Returns the Mesh.
  32657. */
  32658. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32659. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32660. this.scaling.copyFromFloats(1, 1, 1);
  32661. this.position.copyFromFloats(0, 0, 0);
  32662. this.rotation.copyFromFloats(0, 0, 0);
  32663. //only if quaternion is already set
  32664. if (this.rotationQuaternion) {
  32665. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32666. }
  32667. this._worldMatrix = BABYLON.Matrix.Identity();
  32668. return this;
  32669. };
  32670. Object.defineProperty(Mesh.prototype, "_positions", {
  32671. // Cache
  32672. get: function () {
  32673. if (this._geometry) {
  32674. return this._geometry._positions;
  32675. }
  32676. return null;
  32677. },
  32678. enumerable: true,
  32679. configurable: true
  32680. });
  32681. Mesh.prototype._resetPointsArrayCache = function () {
  32682. if (this._geometry) {
  32683. this._geometry._resetPointsArrayCache();
  32684. }
  32685. return this;
  32686. };
  32687. Mesh.prototype._generatePointsArray = function () {
  32688. if (this._geometry) {
  32689. return this._geometry._generatePointsArray();
  32690. }
  32691. return false;
  32692. };
  32693. /**
  32694. * Returns a new Mesh object generated from the current mesh properties.
  32695. * This method must not get confused with createInstance().
  32696. * The parameter `name` is a string, the name given to the new mesh.
  32697. * The optional parameter `newParent` can be any Node object (default `null`).
  32698. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32699. * 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.
  32700. */
  32701. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32702. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32703. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32704. };
  32705. /**
  32706. * Releases resources associated with this mesh.
  32707. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32708. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32709. */
  32710. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32711. var _this = this;
  32712. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32713. this.morphTargetManager = null;
  32714. if (this._geometry) {
  32715. this._geometry.releaseForMesh(this, true);
  32716. }
  32717. // Sources
  32718. var meshes = this.getScene().meshes;
  32719. meshes.forEach(function (abstractMesh) {
  32720. var mesh = abstractMesh;
  32721. if (mesh._source && mesh._source === _this) {
  32722. mesh._source = null;
  32723. }
  32724. });
  32725. this._source = null;
  32726. // Instances
  32727. if (this._instancesBuffer) {
  32728. this._instancesBuffer.dispose();
  32729. this._instancesBuffer = null;
  32730. }
  32731. while (this.instances.length) {
  32732. this.instances[0].dispose();
  32733. }
  32734. // Effect layers.
  32735. var effectLayers = this.getScene().effectLayers;
  32736. for (var i = 0; i < effectLayers.length; i++) {
  32737. var effectLayer = effectLayers[i];
  32738. if (effectLayer) {
  32739. effectLayer._disposeMesh(this);
  32740. }
  32741. }
  32742. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32743. };
  32744. /**
  32745. * Modifies the mesh geometry according to a displacement map.
  32746. * 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.
  32747. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32748. * This method returns nothing.
  32749. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32750. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32751. * 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.
  32752. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32753. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32754. *
  32755. * Returns the Mesh.
  32756. */
  32757. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32758. var _this = this;
  32759. var scene = this.getScene();
  32760. var onload = function (img) {
  32761. // Getting height map data
  32762. var canvas = document.createElement("canvas");
  32763. var context = canvas.getContext("2d");
  32764. var heightMapWidth = img.width;
  32765. var heightMapHeight = img.height;
  32766. canvas.width = heightMapWidth;
  32767. canvas.height = heightMapHeight;
  32768. context.drawImage(img, 0, 0);
  32769. // Create VertexData from map data
  32770. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32771. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32772. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32773. //execute success callback, if set
  32774. if (onSuccess) {
  32775. onSuccess(_this);
  32776. }
  32777. };
  32778. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32779. return this;
  32780. };
  32781. /**
  32782. * Modifies the mesh geometry according to a displacementMap buffer.
  32783. * 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.
  32784. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32785. * This method returns nothing.
  32786. * 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.
  32787. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32788. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32789. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32790. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32791. *
  32792. * Returns the Mesh.
  32793. */
  32794. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32796. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32797. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32798. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32799. return this;
  32800. }
  32801. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32802. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32803. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32804. var position = BABYLON.Vector3.Zero();
  32805. var normal = BABYLON.Vector3.Zero();
  32806. var uv = BABYLON.Vector2.Zero();
  32807. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32808. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32809. for (var index = 0; index < positions.length; index += 3) {
  32810. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32811. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32812. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32813. // Compute height
  32814. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32815. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32816. var pos = (u + v * heightMapWidth) * 4;
  32817. var r = buffer[pos] / 255.0;
  32818. var g = buffer[pos + 1] / 255.0;
  32819. var b = buffer[pos + 2] / 255.0;
  32820. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32821. normal.normalize();
  32822. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32823. position = position.add(normal);
  32824. position.toArray(positions, index);
  32825. }
  32826. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32827. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32828. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32829. return this;
  32830. };
  32831. /**
  32832. * Modify the mesh to get a flat shading rendering.
  32833. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32834. * This method returns the Mesh.
  32835. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32836. */
  32837. Mesh.prototype.convertToFlatShadedMesh = function () {
  32838. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32839. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32840. var kinds = this.getVerticesDataKinds();
  32841. var vbs = {};
  32842. var data = {};
  32843. var newdata = {};
  32844. var updatableNormals = false;
  32845. var kindIndex;
  32846. var kind;
  32847. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32848. kind = kinds[kindIndex];
  32849. var vertexBuffer = this.getVertexBuffer(kind);
  32850. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32851. updatableNormals = vertexBuffer.isUpdatable();
  32852. kinds.splice(kindIndex, 1);
  32853. kindIndex--;
  32854. continue;
  32855. }
  32856. vbs[kind] = vertexBuffer;
  32857. data[kind] = vbs[kind].getData();
  32858. newdata[kind] = [];
  32859. }
  32860. // Save previous submeshes
  32861. var previousSubmeshes = this.subMeshes.slice(0);
  32862. var indices = this.getIndices();
  32863. var totalIndices = this.getTotalIndices();
  32864. // Generating unique vertices per face
  32865. var index;
  32866. for (index = 0; index < totalIndices; index++) {
  32867. var vertexIndex = indices[index];
  32868. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32869. kind = kinds[kindIndex];
  32870. var stride = vbs[kind].getStrideSize();
  32871. for (var offset = 0; offset < stride; offset++) {
  32872. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32873. }
  32874. }
  32875. }
  32876. // Updating faces & normal
  32877. var normals = [];
  32878. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32879. for (index = 0; index < totalIndices; index += 3) {
  32880. indices[index] = index;
  32881. indices[index + 1] = index + 1;
  32882. indices[index + 2] = index + 2;
  32883. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32884. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32885. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32886. var p1p2 = p1.subtract(p2);
  32887. var p3p2 = p3.subtract(p2);
  32888. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32889. // Store same normals for every vertex
  32890. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32891. normals.push(normal.x);
  32892. normals.push(normal.y);
  32893. normals.push(normal.z);
  32894. }
  32895. }
  32896. this.setIndices(indices);
  32897. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32898. // Updating vertex buffers
  32899. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32900. kind = kinds[kindIndex];
  32901. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32902. }
  32903. // Updating submeshes
  32904. this.releaseSubMeshes();
  32905. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32906. var previousOne = previousSubmeshes[submeshIndex];
  32907. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32908. }
  32909. this.synchronizeInstances();
  32910. return this;
  32911. };
  32912. /**
  32913. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32914. * In other words, more vertices, no more indices and a single bigger VBO.
  32915. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32916. * Returns the Mesh.
  32917. */
  32918. Mesh.prototype.convertToUnIndexedMesh = function () {
  32919. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32920. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32921. var kinds = this.getVerticesDataKinds();
  32922. var vbs = {};
  32923. var data = {};
  32924. var newdata = {};
  32925. var kindIndex;
  32926. var kind;
  32927. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32928. kind = kinds[kindIndex];
  32929. var vertexBuffer = this.getVertexBuffer(kind);
  32930. vbs[kind] = vertexBuffer;
  32931. data[kind] = vbs[kind].getData();
  32932. newdata[kind] = [];
  32933. }
  32934. // Save previous submeshes
  32935. var previousSubmeshes = this.subMeshes.slice(0);
  32936. var indices = this.getIndices();
  32937. var totalIndices = this.getTotalIndices();
  32938. // Generating unique vertices per face
  32939. var index;
  32940. for (index = 0; index < totalIndices; index++) {
  32941. var vertexIndex = indices[index];
  32942. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32943. kind = kinds[kindIndex];
  32944. var stride = vbs[kind].getStrideSize();
  32945. for (var offset = 0; offset < stride; offset++) {
  32946. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32947. }
  32948. }
  32949. }
  32950. // Updating indices
  32951. for (index = 0; index < totalIndices; index += 3) {
  32952. indices[index] = index;
  32953. indices[index + 1] = index + 1;
  32954. indices[index + 2] = index + 2;
  32955. }
  32956. this.setIndices(indices);
  32957. // Updating vertex buffers
  32958. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32959. kind = kinds[kindIndex];
  32960. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32961. }
  32962. // Updating submeshes
  32963. this.releaseSubMeshes();
  32964. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32965. var previousOne = previousSubmeshes[submeshIndex];
  32966. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32967. }
  32968. this._unIndexed = true;
  32969. this.synchronizeInstances();
  32970. return this;
  32971. };
  32972. /**
  32973. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32974. * This method returns the Mesh.
  32975. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32976. */
  32977. Mesh.prototype.flipFaces = function (flipNormals) {
  32978. if (flipNormals === void 0) { flipNormals = false; }
  32979. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32980. var i;
  32981. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32982. for (i = 0; i < vertex_data.normals.length; i++) {
  32983. vertex_data.normals[i] *= -1;
  32984. }
  32985. }
  32986. if (vertex_data.indices) {
  32987. var temp;
  32988. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32989. // reassign indices
  32990. temp = vertex_data.indices[i + 1];
  32991. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32992. vertex_data.indices[i + 2] = temp;
  32993. }
  32994. }
  32995. vertex_data.applyToMesh(this);
  32996. return this;
  32997. };
  32998. // Instances
  32999. /**
  33000. * Creates a new InstancedMesh object from the mesh model.
  33001. * An instance shares the same properties and the same material than its model.
  33002. * Only these properties of each instance can then be set individually :
  33003. * - position
  33004. * - rotation
  33005. * - rotationQuaternion
  33006. * - setPivotMatrix
  33007. * - scaling
  33008. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33009. * Warning : this method is not supported for Line mesh and LineSystem
  33010. */
  33011. Mesh.prototype.createInstance = function (name) {
  33012. return new BABYLON.InstancedMesh(name, this);
  33013. };
  33014. /**
  33015. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33016. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33017. * This method returns the Mesh.
  33018. */
  33019. Mesh.prototype.synchronizeInstances = function () {
  33020. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33021. var instance = this.instances[instanceIndex];
  33022. instance._syncSubMeshes();
  33023. }
  33024. return this;
  33025. };
  33026. /**
  33027. * Simplify the mesh according to the given array of settings.
  33028. * Function will return immediately and will simplify async. It returns the Mesh.
  33029. * @param settings a collection of simplification settings.
  33030. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33031. * @param type the type of simplification to run.
  33032. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33033. */
  33034. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33035. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33036. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33037. this.getScene().simplificationQueue.addTask({
  33038. settings: settings,
  33039. parallelProcessing: parallelProcessing,
  33040. mesh: this,
  33041. simplificationType: simplificationType,
  33042. successCallback: successCallback
  33043. });
  33044. return this;
  33045. };
  33046. /**
  33047. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33048. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33049. * This should be used together with the simplification to avoid disappearing triangles.
  33050. * Returns the Mesh.
  33051. * @param successCallback an optional success callback to be called after the optimization finished.
  33052. */
  33053. Mesh.prototype.optimizeIndices = function (successCallback) {
  33054. var _this = this;
  33055. var indices = this.getIndices();
  33056. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33057. if (!positions || !indices) {
  33058. return this;
  33059. }
  33060. var vectorPositions = new Array();
  33061. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33062. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33063. }
  33064. var dupes = new Array();
  33065. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33066. var realPos = vectorPositions.length - 1 - iteration;
  33067. var testedPosition = vectorPositions[realPos];
  33068. for (var j = 0; j < realPos; ++j) {
  33069. var againstPosition = vectorPositions[j];
  33070. if (testedPosition.equals(againstPosition)) {
  33071. dupes[realPos] = j;
  33072. break;
  33073. }
  33074. }
  33075. }, function () {
  33076. for (var i = 0; i < indices.length; ++i) {
  33077. indices[i] = dupes[indices[i]] || indices[i];
  33078. }
  33079. //indices are now reordered
  33080. var originalSubMeshes = _this.subMeshes.slice(0);
  33081. _this.setIndices(indices);
  33082. _this.subMeshes = originalSubMeshes;
  33083. if (successCallback) {
  33084. successCallback(_this);
  33085. }
  33086. });
  33087. return this;
  33088. };
  33089. Mesh.prototype.serialize = function (serializationObject) {
  33090. serializationObject.name = this.name;
  33091. serializationObject.id = this.id;
  33092. serializationObject.type = this.getClassName();
  33093. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33094. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33095. }
  33096. serializationObject.position = this.position.asArray();
  33097. if (this.rotationQuaternion) {
  33098. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33099. }
  33100. else if (this.rotation) {
  33101. serializationObject.rotation = this.rotation.asArray();
  33102. }
  33103. serializationObject.scaling = this.scaling.asArray();
  33104. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33105. serializationObject.isEnabled = this.isEnabled(false);
  33106. serializationObject.isVisible = this.isVisible;
  33107. serializationObject.infiniteDistance = this.infiniteDistance;
  33108. serializationObject.pickable = this.isPickable;
  33109. serializationObject.receiveShadows = this.receiveShadows;
  33110. serializationObject.billboardMode = this.billboardMode;
  33111. serializationObject.visibility = this.visibility;
  33112. serializationObject.checkCollisions = this.checkCollisions;
  33113. serializationObject.isBlocker = this.isBlocker;
  33114. // Parent
  33115. if (this.parent) {
  33116. serializationObject.parentId = this.parent.id;
  33117. }
  33118. // Geometry
  33119. serializationObject.isUnIndexed = this.isUnIndexed;
  33120. var geometry = this._geometry;
  33121. if (geometry) {
  33122. var geometryId = geometry.id;
  33123. serializationObject.geometryId = geometryId;
  33124. // SubMeshes
  33125. serializationObject.subMeshes = [];
  33126. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33127. var subMesh = this.subMeshes[subIndex];
  33128. serializationObject.subMeshes.push({
  33129. materialIndex: subMesh.materialIndex,
  33130. verticesStart: subMesh.verticesStart,
  33131. verticesCount: subMesh.verticesCount,
  33132. indexStart: subMesh.indexStart,
  33133. indexCount: subMesh.indexCount
  33134. });
  33135. }
  33136. }
  33137. // Material
  33138. if (this.material) {
  33139. serializationObject.materialId = this.material.id;
  33140. }
  33141. else {
  33142. this.material = null;
  33143. }
  33144. // Morph targets
  33145. if (this.morphTargetManager) {
  33146. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33147. }
  33148. // Skeleton
  33149. if (this.skeleton) {
  33150. serializationObject.skeletonId = this.skeleton.id;
  33151. }
  33152. // Physics
  33153. //TODO implement correct serialization for physics impostors.
  33154. var impostor = this.getPhysicsImpostor();
  33155. if (impostor) {
  33156. serializationObject.physicsMass = impostor.getParam("mass");
  33157. serializationObject.physicsFriction = impostor.getParam("friction");
  33158. serializationObject.physicsRestitution = impostor.getParam("mass");
  33159. serializationObject.physicsImpostor = impostor.type;
  33160. }
  33161. // Metadata
  33162. if (this.metadata) {
  33163. serializationObject.metadata = this.metadata;
  33164. }
  33165. // Instances
  33166. serializationObject.instances = [];
  33167. for (var index = 0; index < this.instances.length; index++) {
  33168. var instance = this.instances[index];
  33169. var serializationInstance = {
  33170. name: instance.name,
  33171. id: instance.id,
  33172. position: instance.position.asArray(),
  33173. scaling: instance.scaling.asArray()
  33174. };
  33175. if (instance.rotationQuaternion) {
  33176. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33177. }
  33178. else if (instance.rotation) {
  33179. serializationInstance.rotation = instance.rotation.asArray();
  33180. }
  33181. serializationObject.instances.push(serializationInstance);
  33182. // Animations
  33183. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33184. serializationInstance.ranges = instance.serializeAnimationRanges();
  33185. }
  33186. //
  33187. // Animations
  33188. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33189. serializationObject.ranges = this.serializeAnimationRanges();
  33190. // Layer mask
  33191. serializationObject.layerMask = this.layerMask;
  33192. // Alpha
  33193. serializationObject.alphaIndex = this.alphaIndex;
  33194. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33195. // Overlay
  33196. serializationObject.overlayAlpha = this.overlayAlpha;
  33197. serializationObject.overlayColor = this.overlayColor.asArray();
  33198. serializationObject.renderOverlay = this.renderOverlay;
  33199. // Fog
  33200. serializationObject.applyFog = this.applyFog;
  33201. // Action Manager
  33202. if (this.actionManager) {
  33203. serializationObject.actions = this.actionManager.serialize(this.name);
  33204. }
  33205. };
  33206. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33207. if (!this.geometry) {
  33208. return;
  33209. }
  33210. this._markSubMeshesAsAttributesDirty();
  33211. var morphTargetManager = this._morphTargetManager;
  33212. if (morphTargetManager && morphTargetManager.vertexCount) {
  33213. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33214. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33215. this.morphTargetManager = null;
  33216. return;
  33217. }
  33218. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33219. var morphTarget = morphTargetManager.getActiveTarget(index);
  33220. var positions = morphTarget.getPositions();
  33221. if (!positions) {
  33222. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33223. return;
  33224. }
  33225. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33226. var normals = morphTarget.getNormals();
  33227. if (normals) {
  33228. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33229. }
  33230. var tangents = morphTarget.getTangents();
  33231. if (tangents) {
  33232. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33233. }
  33234. }
  33235. }
  33236. else {
  33237. var index = 0;
  33238. // Positions
  33239. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33240. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33241. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33242. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33243. }
  33244. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33245. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33246. }
  33247. index++;
  33248. }
  33249. }
  33250. };
  33251. // Statics
  33252. /**
  33253. * Returns a new Mesh object parsed from the source provided.
  33254. * The parameter `parsedMesh` is the source.
  33255. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33256. */
  33257. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33258. var mesh;
  33259. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33260. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33261. }
  33262. else {
  33263. mesh = new Mesh(parsedMesh.name, scene);
  33264. }
  33265. mesh.id = parsedMesh.id;
  33266. if (BABYLON.Tags) {
  33267. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33268. }
  33269. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33270. if (parsedMesh.metadata !== undefined) {
  33271. mesh.metadata = parsedMesh.metadata;
  33272. }
  33273. if (parsedMesh.rotationQuaternion) {
  33274. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33275. }
  33276. else if (parsedMesh.rotation) {
  33277. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33278. }
  33279. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33280. if (parsedMesh.localMatrix) {
  33281. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33282. }
  33283. else if (parsedMesh.pivotMatrix) {
  33284. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33285. }
  33286. mesh.setEnabled(parsedMesh.isEnabled);
  33287. mesh.isVisible = parsedMesh.isVisible;
  33288. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33289. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33290. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33291. if (parsedMesh.applyFog !== undefined) {
  33292. mesh.applyFog = parsedMesh.applyFog;
  33293. }
  33294. if (parsedMesh.pickable !== undefined) {
  33295. mesh.isPickable = parsedMesh.pickable;
  33296. }
  33297. if (parsedMesh.alphaIndex !== undefined) {
  33298. mesh.alphaIndex = parsedMesh.alphaIndex;
  33299. }
  33300. mesh.receiveShadows = parsedMesh.receiveShadows;
  33301. mesh.billboardMode = parsedMesh.billboardMode;
  33302. if (parsedMesh.visibility !== undefined) {
  33303. mesh.visibility = parsedMesh.visibility;
  33304. }
  33305. mesh.checkCollisions = parsedMesh.checkCollisions;
  33306. if (parsedMesh.isBlocker !== undefined) {
  33307. mesh.isBlocker = parsedMesh.isBlocker;
  33308. }
  33309. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33310. // freezeWorldMatrix
  33311. if (parsedMesh.freezeWorldMatrix) {
  33312. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33313. }
  33314. // Parent
  33315. if (parsedMesh.parentId) {
  33316. mesh._waitingParentId = parsedMesh.parentId;
  33317. }
  33318. // Actions
  33319. if (parsedMesh.actions !== undefined) {
  33320. mesh._waitingActions = parsedMesh.actions;
  33321. }
  33322. // Overlay
  33323. if (parsedMesh.overlayAlpha !== undefined) {
  33324. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33325. }
  33326. if (parsedMesh.overlayColor !== undefined) {
  33327. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33328. }
  33329. if (parsedMesh.renderOverlay !== undefined) {
  33330. mesh.renderOverlay = parsedMesh.renderOverlay;
  33331. }
  33332. // Geometry
  33333. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33334. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33335. if (parsedMesh.delayLoadingFile) {
  33336. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33337. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33338. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33339. if (parsedMesh._binaryInfo) {
  33340. mesh._binaryInfo = parsedMesh._binaryInfo;
  33341. }
  33342. mesh._delayInfo = [];
  33343. if (parsedMesh.hasUVs) {
  33344. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33345. }
  33346. if (parsedMesh.hasUVs2) {
  33347. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33348. }
  33349. if (parsedMesh.hasUVs3) {
  33350. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33351. }
  33352. if (parsedMesh.hasUVs4) {
  33353. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33354. }
  33355. if (parsedMesh.hasUVs5) {
  33356. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33357. }
  33358. if (parsedMesh.hasUVs6) {
  33359. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33360. }
  33361. if (parsedMesh.hasColors) {
  33362. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33363. }
  33364. if (parsedMesh.hasMatricesIndices) {
  33365. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33366. }
  33367. if (parsedMesh.hasMatricesWeights) {
  33368. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33369. }
  33370. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33371. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33372. mesh._checkDelayState();
  33373. }
  33374. }
  33375. else {
  33376. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33377. }
  33378. // Material
  33379. if (parsedMesh.materialId) {
  33380. mesh.setMaterialByID(parsedMesh.materialId);
  33381. }
  33382. else {
  33383. mesh.material = null;
  33384. }
  33385. // Morph targets
  33386. if (parsedMesh.morphTargetManagerId > -1) {
  33387. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33388. }
  33389. // Skeleton
  33390. if (parsedMesh.skeletonId > -1) {
  33391. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33392. if (parsedMesh.numBoneInfluencers) {
  33393. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33394. }
  33395. }
  33396. // Animations
  33397. if (parsedMesh.animations) {
  33398. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33399. var parsedAnimation = parsedMesh.animations[animationIndex];
  33400. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33401. }
  33402. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33403. }
  33404. if (parsedMesh.autoAnimate) {
  33405. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33406. }
  33407. // Layer Mask
  33408. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33409. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33410. }
  33411. else {
  33412. mesh.layerMask = 0x0FFFFFFF;
  33413. }
  33414. // Physics
  33415. if (parsedMesh.physicsImpostor) {
  33416. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33417. mass: parsedMesh.physicsMass,
  33418. friction: parsedMesh.physicsFriction,
  33419. restitution: parsedMesh.physicsRestitution
  33420. }, scene);
  33421. }
  33422. // Instances
  33423. if (parsedMesh.instances) {
  33424. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33425. var parsedInstance = parsedMesh.instances[index];
  33426. var instance = mesh.createInstance(parsedInstance.name);
  33427. if (parsedInstance.id) {
  33428. instance.id = parsedInstance.id;
  33429. }
  33430. if (BABYLON.Tags) {
  33431. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33432. }
  33433. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33434. if (parsedInstance.parentId) {
  33435. instance._waitingParentId = parsedInstance.parentId;
  33436. }
  33437. if (parsedInstance.rotationQuaternion) {
  33438. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33439. }
  33440. else if (parsedInstance.rotation) {
  33441. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33442. }
  33443. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33444. instance.checkCollisions = mesh.checkCollisions;
  33445. if (parsedMesh.animations) {
  33446. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33447. parsedAnimation = parsedMesh.animations[animationIndex];
  33448. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33449. }
  33450. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33451. }
  33452. }
  33453. }
  33454. return mesh;
  33455. };
  33456. /**
  33457. * Creates a ribbon mesh.
  33458. * Please consider using the same method from the MeshBuilder class instead.
  33459. * 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.
  33460. *
  33461. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33462. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33463. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33464. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33465. * 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.
  33466. * 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.
  33467. * 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
  33468. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33469. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33471. */
  33472. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33473. if (closeArray === void 0) { closeArray = false; }
  33474. if (updatable === void 0) { updatable = false; }
  33475. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33476. pathArray: pathArray,
  33477. closeArray: closeArray,
  33478. closePath: closePath,
  33479. offset: offset,
  33480. updatable: updatable,
  33481. sideOrientation: sideOrientation,
  33482. instance: instance
  33483. }, scene);
  33484. };
  33485. /**
  33486. * Creates a plane polygonal mesh. By default, this is a disc.
  33487. * Please consider using the same method from the MeshBuilder class instead.
  33488. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33489. * 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.
  33490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33491. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33493. */
  33494. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33495. if (scene === void 0) { scene = null; }
  33496. var options = {
  33497. radius: radius,
  33498. tessellation: tessellation,
  33499. sideOrientation: sideOrientation,
  33500. updatable: updatable
  33501. };
  33502. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33503. };
  33504. /**
  33505. * Creates a box mesh.
  33506. * Please consider using the same method from the MeshBuilder class instead.
  33507. * The parameter `size` sets the size (float) of each box side (default 1).
  33508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33509. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33511. */
  33512. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33513. if (scene === void 0) { scene = null; }
  33514. var options = {
  33515. size: size,
  33516. sideOrientation: sideOrientation,
  33517. updatable: updatable
  33518. };
  33519. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33520. };
  33521. /**
  33522. * Creates a sphere mesh.
  33523. * Please consider using the same method from the MeshBuilder class instead.
  33524. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33525. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33527. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33529. */
  33530. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33531. var options = {
  33532. segments: segments,
  33533. diameterX: diameter,
  33534. diameterY: diameter,
  33535. diameterZ: diameter,
  33536. sideOrientation: sideOrientation,
  33537. updatable: updatable
  33538. };
  33539. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33540. };
  33541. /**
  33542. * Creates a cylinder or a cone mesh.
  33543. * Please consider using the same method from the MeshBuilder class instead.
  33544. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33545. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33546. * 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.
  33547. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33548. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33550. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33552. */
  33553. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33554. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33555. if (scene !== undefined) {
  33556. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33557. updatable = scene;
  33558. }
  33559. scene = subdivisions;
  33560. subdivisions = 1;
  33561. }
  33562. var options = {
  33563. height: height,
  33564. diameterTop: diameterTop,
  33565. diameterBottom: diameterBottom,
  33566. tessellation: tessellation,
  33567. subdivisions: subdivisions,
  33568. sideOrientation: sideOrientation,
  33569. updatable: updatable
  33570. };
  33571. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33572. };
  33573. // Torus (Code from SharpDX.org)
  33574. /**
  33575. * Creates a torus mesh.
  33576. * Please consider using the same method from the MeshBuilder class instead.
  33577. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33578. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33579. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33581. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33583. */
  33584. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33585. var options = {
  33586. diameter: diameter,
  33587. thickness: thickness,
  33588. tessellation: tessellation,
  33589. sideOrientation: sideOrientation,
  33590. updatable: updatable
  33591. };
  33592. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33593. };
  33594. /**
  33595. * Creates a torus knot mesh.
  33596. * Please consider using the same method from the MeshBuilder class instead.
  33597. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33598. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33599. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33600. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33602. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33604. */
  33605. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33606. var options = {
  33607. radius: radius,
  33608. tube: tube,
  33609. radialSegments: radialSegments,
  33610. tubularSegments: tubularSegments,
  33611. p: p,
  33612. q: q,
  33613. sideOrientation: sideOrientation,
  33614. updatable: updatable
  33615. };
  33616. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33617. };
  33618. /**
  33619. * Creates a line mesh.
  33620. * Please consider using the same method from the MeshBuilder class instead.
  33621. * 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.
  33622. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33623. * The parameter `points` is an array successive Vector3.
  33624. * 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
  33625. * When updating an instance, remember that only point positions can change, not the number of points.
  33626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33627. */
  33628. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33629. if (scene === void 0) { scene = null; }
  33630. if (updatable === void 0) { updatable = false; }
  33631. if (instance === void 0) { instance = null; }
  33632. var options = {
  33633. points: points,
  33634. updatable: updatable,
  33635. instance: instance
  33636. };
  33637. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33638. };
  33639. /**
  33640. * Creates a dashed line mesh.
  33641. * Please consider using the same method from the MeshBuilder class instead.
  33642. * 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.
  33643. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33644. * The parameter `points` is an array successive Vector3.
  33645. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33646. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33647. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33648. * 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
  33649. * When updating an instance, remember that only point positions can change, not the number of points.
  33650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33651. */
  33652. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33653. if (scene === void 0) { scene = null; }
  33654. var options = {
  33655. points: points,
  33656. dashSize: dashSize,
  33657. gapSize: gapSize,
  33658. dashNb: dashNb,
  33659. updatable: updatable,
  33660. instance: instance
  33661. };
  33662. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33663. };
  33664. /**
  33665. * Creates a polygon mesh.
  33666. * Please consider using the same method from the MeshBuilder class instead.
  33667. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33668. * 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.
  33669. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33671. * Remember you can only change the shape positions, not their number when updating a polygon.
  33672. */
  33673. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33674. var options = {
  33675. shape: shape,
  33676. holes: holes,
  33677. updatable: updatable,
  33678. sideOrientation: sideOrientation
  33679. };
  33680. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33681. };
  33682. /**
  33683. * Creates an extruded polygon mesh, with depth in the Y direction.
  33684. * Please consider using the same method from the MeshBuilder class instead.
  33685. */
  33686. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33687. var options = {
  33688. shape: shape,
  33689. holes: holes,
  33690. depth: depth,
  33691. updatable: updatable,
  33692. sideOrientation: sideOrientation
  33693. };
  33694. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33695. };
  33696. /**
  33697. * Creates an extruded shape mesh.
  33698. * 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.
  33699. * Please consider using the same method from the MeshBuilder class instead.
  33700. *
  33701. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33702. * 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
  33703. * extruded along the Z axis.
  33704. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33705. * 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.
  33706. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33707. * 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
  33708. * 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
  33709. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33711. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33713. */
  33714. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33715. if (scene === void 0) { scene = null; }
  33716. var options = {
  33717. shape: shape,
  33718. path: path,
  33719. scale: scale,
  33720. rotation: rotation,
  33721. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33722. sideOrientation: sideOrientation,
  33723. instance: instance,
  33724. updatable: updatable
  33725. };
  33726. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33727. };
  33728. /**
  33729. * Creates an custom extruded shape mesh.
  33730. * 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.
  33731. * Please consider using the same method from the MeshBuilder class instead.
  33732. *
  33733. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33734. * 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
  33735. * extruded along the Z axis.
  33736. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33737. * 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
  33738. * and the distance of this point from the begining of the path :
  33739. * ```javascript
  33740. * var rotationFunction = function(i, distance) {
  33741. * // do things
  33742. * return rotationValue; }
  33743. * ```
  33744. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33745. * 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
  33746. * and the distance of this point from the begining of the path :
  33747. * ```javascript
  33748. * var scaleFunction = function(i, distance) {
  33749. * // do things
  33750. * return scaleValue;}
  33751. * ```
  33752. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33753. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33754. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33755. * 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
  33756. * 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
  33757. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33759. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33761. */
  33762. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33763. var options = {
  33764. shape: shape,
  33765. path: path,
  33766. scaleFunction: scaleFunction,
  33767. rotationFunction: rotationFunction,
  33768. ribbonCloseArray: ribbonCloseArray,
  33769. ribbonClosePath: ribbonClosePath,
  33770. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33771. sideOrientation: sideOrientation,
  33772. instance: instance,
  33773. updatable: updatable
  33774. };
  33775. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33776. };
  33777. /**
  33778. * Creates lathe mesh.
  33779. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33780. * Please consider using the same method from the MeshBuilder class instead.
  33781. * 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
  33782. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33783. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33784. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33786. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33788. */
  33789. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33790. var options = {
  33791. shape: shape,
  33792. radius: radius,
  33793. tessellation: tessellation,
  33794. sideOrientation: sideOrientation,
  33795. updatable: updatable
  33796. };
  33797. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33798. };
  33799. /**
  33800. * Creates a plane mesh.
  33801. * Please consider using the same method from the MeshBuilder class instead.
  33802. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33804. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33806. */
  33807. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33808. var options = {
  33809. size: size,
  33810. width: size,
  33811. height: size,
  33812. sideOrientation: sideOrientation,
  33813. updatable: updatable
  33814. };
  33815. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33816. };
  33817. /**
  33818. * Creates a ground mesh.
  33819. * Please consider using the same method from the MeshBuilder class instead.
  33820. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33821. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33823. */
  33824. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33825. var options = {
  33826. width: width,
  33827. height: height,
  33828. subdivisions: subdivisions,
  33829. updatable: updatable
  33830. };
  33831. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33832. };
  33833. /**
  33834. * Creates a tiled ground mesh.
  33835. * Please consider using the same method from the MeshBuilder class instead.
  33836. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33837. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33838. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33839. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33840. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33841. * numbers of subdivisions on the ground width and height of each tile.
  33842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33843. */
  33844. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33845. var options = {
  33846. xmin: xmin,
  33847. zmin: zmin,
  33848. xmax: xmax,
  33849. zmax: zmax,
  33850. subdivisions: subdivisions,
  33851. precision: precision,
  33852. updatable: updatable
  33853. };
  33854. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33855. };
  33856. /**
  33857. * Creates a ground mesh from a height map.
  33858. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33859. * Please consider using the same method from the MeshBuilder class instead.
  33860. * The parameter `url` sets the URL of the height map image resource.
  33861. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33862. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33863. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33864. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33865. * 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).
  33866. * This function is passed the newly built mesh :
  33867. * ```javascript
  33868. * function(mesh) { // do things
  33869. * return; }
  33870. * ```
  33871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33872. */
  33873. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33874. var options = {
  33875. width: width,
  33876. height: height,
  33877. subdivisions: subdivisions,
  33878. minHeight: minHeight,
  33879. maxHeight: maxHeight,
  33880. updatable: updatable,
  33881. onReady: onReady
  33882. };
  33883. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33884. };
  33885. /**
  33886. * Creates a tube mesh.
  33887. * 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.
  33888. * Please consider using the same method from the MeshBuilder class instead.
  33889. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33890. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33891. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33892. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33893. * 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.
  33894. * It must return a radius value (positive float) :
  33895. * ```javascript
  33896. * var radiusFunction = function(i, distance) {
  33897. * // do things
  33898. * return radius; }
  33899. * ```
  33900. * 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
  33901. * 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
  33902. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33903. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33905. */
  33906. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33907. var options = {
  33908. path: path,
  33909. radius: radius,
  33910. tessellation: tessellation,
  33911. radiusFunction: radiusFunction,
  33912. arc: 1,
  33913. cap: cap,
  33914. updatable: updatable,
  33915. sideOrientation: sideOrientation,
  33916. instance: instance
  33917. };
  33918. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33919. };
  33920. /**
  33921. * Creates a polyhedron mesh.
  33922. * Please consider using the same method from the MeshBuilder class instead.
  33923. * 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
  33924. * to choose the wanted type.
  33925. * The parameter `size` (positive float, default 1) sets the polygon size.
  33926. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33927. * 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`.
  33928. * 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
  33929. * 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)`).
  33930. * 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
  33931. * 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.
  33932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33933. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33935. */
  33936. Mesh.CreatePolyhedron = function (name, options, scene) {
  33937. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33938. };
  33939. /**
  33940. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33941. * Please consider using the same method from the MeshBuilder class instead.
  33942. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33943. * 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`).
  33944. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33945. * 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.
  33946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33947. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33949. */
  33950. Mesh.CreateIcoSphere = function (name, options, scene) {
  33951. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33952. };
  33953. /**
  33954. * Creates a decal mesh.
  33955. * Please consider using the same method from the MeshBuilder class instead.
  33956. * 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.
  33957. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33958. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33959. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33960. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33961. */
  33962. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33963. var options = {
  33964. position: position,
  33965. normal: normal,
  33966. size: size,
  33967. angle: angle
  33968. };
  33969. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33970. };
  33971. // Skeletons
  33972. /**
  33973. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33974. */
  33975. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33976. if (!this._sourcePositions) {
  33977. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33978. if (!source) {
  33979. return this._sourcePositions;
  33980. }
  33981. this._sourcePositions = new Float32Array(source);
  33982. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33983. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33984. }
  33985. }
  33986. return this._sourcePositions;
  33987. };
  33988. /**
  33989. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33990. */
  33991. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33992. if (!this._sourceNormals) {
  33993. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33994. if (!source) {
  33995. return this._sourceNormals;
  33996. }
  33997. this._sourceNormals = new Float32Array(source);
  33998. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33999. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34000. }
  34001. }
  34002. return this._sourceNormals;
  34003. };
  34004. /**
  34005. * Updates the vertex buffer by applying transformation from the bones.
  34006. * Returns the Mesh.
  34007. *
  34008. * @param {skeleton} skeleton to apply
  34009. */
  34010. Mesh.prototype.applySkeleton = function (skeleton) {
  34011. if (!this.geometry) {
  34012. return this;
  34013. }
  34014. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34015. return this;
  34016. }
  34017. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34018. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34019. return this;
  34020. }
  34021. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34022. return this;
  34023. }
  34024. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34025. return this;
  34026. }
  34027. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34028. return this;
  34029. }
  34030. if (!this._sourcePositions) {
  34031. var submeshes = this.subMeshes.slice();
  34032. this.setPositionsForCPUSkinning();
  34033. this.subMeshes = submeshes;
  34034. }
  34035. if (!this._sourceNormals) {
  34036. this.setNormalsForCPUSkinning();
  34037. }
  34038. // positionsData checks for not being Float32Array will only pass at most once
  34039. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34040. if (!positionsData) {
  34041. return this;
  34042. }
  34043. if (!(positionsData instanceof Float32Array)) {
  34044. positionsData = new Float32Array(positionsData);
  34045. }
  34046. // normalsData checks for not being Float32Array will only pass at most once
  34047. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34048. if (!normalsData) {
  34049. return this;
  34050. }
  34051. if (!(normalsData instanceof Float32Array)) {
  34052. normalsData = new Float32Array(normalsData);
  34053. }
  34054. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34055. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34056. if (!matricesWeightsData || !matricesIndicesData) {
  34057. return this;
  34058. }
  34059. var needExtras = this.numBoneInfluencers > 4;
  34060. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34061. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34062. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34063. var tempVector3 = BABYLON.Vector3.Zero();
  34064. var finalMatrix = new BABYLON.Matrix();
  34065. var tempMatrix = new BABYLON.Matrix();
  34066. var matWeightIdx = 0;
  34067. var inf;
  34068. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34069. var weight;
  34070. for (inf = 0; inf < 4; inf++) {
  34071. weight = matricesWeightsData[matWeightIdx + inf];
  34072. if (weight > 0) {
  34073. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34074. finalMatrix.addToSelf(tempMatrix);
  34075. }
  34076. else
  34077. break;
  34078. }
  34079. if (needExtras) {
  34080. for (inf = 0; inf < 4; inf++) {
  34081. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34082. if (weight > 0) {
  34083. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34084. finalMatrix.addToSelf(tempMatrix);
  34085. }
  34086. else
  34087. break;
  34088. }
  34089. }
  34090. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34091. tempVector3.toArray(positionsData, index);
  34092. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34093. tempVector3.toArray(normalsData, index);
  34094. finalMatrix.reset();
  34095. }
  34096. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34097. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34098. return this;
  34099. };
  34100. // Tools
  34101. /**
  34102. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34103. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34104. */
  34105. Mesh.MinMax = function (meshes) {
  34106. var minVector = null;
  34107. var maxVector = null;
  34108. meshes.forEach(function (mesh, index, array) {
  34109. var boundingInfo = mesh.getBoundingInfo();
  34110. var boundingBox = boundingInfo.boundingBox;
  34111. if (!minVector || !maxVector) {
  34112. minVector = boundingBox.minimumWorld;
  34113. maxVector = boundingBox.maximumWorld;
  34114. }
  34115. else {
  34116. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34117. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34118. }
  34119. });
  34120. if (!minVector || !maxVector) {
  34121. return {
  34122. min: BABYLON.Vector3.Zero(),
  34123. max: BABYLON.Vector3.Zero()
  34124. };
  34125. }
  34126. return {
  34127. min: minVector,
  34128. max: maxVector
  34129. };
  34130. };
  34131. /**
  34132. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34133. */
  34134. Mesh.Center = function (meshesOrMinMaxVector) {
  34135. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34136. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34137. };
  34138. /**
  34139. * Merge the array of meshes into a single mesh for performance reasons.
  34140. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34141. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34142. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34143. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34144. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34145. */
  34146. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34147. if (disposeSource === void 0) { disposeSource = true; }
  34148. var index;
  34149. if (!allow32BitsIndices) {
  34150. var totalVertices = 0;
  34151. // Counting vertices
  34152. for (index = 0; index < meshes.length; index++) {
  34153. if (meshes[index]) {
  34154. totalVertices += meshes[index].getTotalVertices();
  34155. if (totalVertices > 65536) {
  34156. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34157. return null;
  34158. }
  34159. }
  34160. }
  34161. }
  34162. // Merge
  34163. var vertexData = null;
  34164. var otherVertexData;
  34165. var indiceArray = new Array();
  34166. var source = null;
  34167. for (index = 0; index < meshes.length; index++) {
  34168. if (meshes[index]) {
  34169. meshes[index].computeWorldMatrix(true);
  34170. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34171. otherVertexData.transform(meshes[index].getWorldMatrix());
  34172. if (vertexData) {
  34173. vertexData.merge(otherVertexData);
  34174. }
  34175. else {
  34176. vertexData = otherVertexData;
  34177. source = meshes[index];
  34178. }
  34179. if (subdivideWithSubMeshes) {
  34180. indiceArray.push(meshes[index].getTotalIndices());
  34181. }
  34182. }
  34183. }
  34184. source = source;
  34185. if (!meshSubclass) {
  34186. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34187. }
  34188. vertexData.applyToMesh(meshSubclass);
  34189. // Setting properties
  34190. meshSubclass.material = source.material;
  34191. meshSubclass.checkCollisions = source.checkCollisions;
  34192. // Cleaning
  34193. if (disposeSource) {
  34194. for (index = 0; index < meshes.length; index++) {
  34195. if (meshes[index]) {
  34196. meshes[index].dispose();
  34197. }
  34198. }
  34199. }
  34200. // Subdivide
  34201. if (subdivideWithSubMeshes) {
  34202. //-- Suppresions du submesh global
  34203. meshSubclass.releaseSubMeshes();
  34204. index = 0;
  34205. var offset = 0;
  34206. //-- aplique la subdivision en fonction du tableau d'indices
  34207. while (index < indiceArray.length) {
  34208. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34209. offset += indiceArray[index];
  34210. index++;
  34211. }
  34212. }
  34213. return meshSubclass;
  34214. };
  34215. // Consts
  34216. Mesh._FRONTSIDE = 0;
  34217. Mesh._BACKSIDE = 1;
  34218. Mesh._DOUBLESIDE = 2;
  34219. Mesh._DEFAULTSIDE = 0;
  34220. Mesh._NO_CAP = 0;
  34221. Mesh._CAP_START = 1;
  34222. Mesh._CAP_END = 2;
  34223. Mesh._CAP_ALL = 3;
  34224. return Mesh;
  34225. }(BABYLON.AbstractMesh));
  34226. BABYLON.Mesh = Mesh;
  34227. })(BABYLON || (BABYLON = {}));
  34228. //# sourceMappingURL=babylon.mesh.js.map
  34229. var BABYLON;
  34230. (function (BABYLON) {
  34231. var BaseSubMesh = /** @class */ (function () {
  34232. function BaseSubMesh() {
  34233. }
  34234. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34235. get: function () {
  34236. return this._materialEffect;
  34237. },
  34238. enumerable: true,
  34239. configurable: true
  34240. });
  34241. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34242. if (defines === void 0) { defines = null; }
  34243. if (this._materialEffect === effect) {
  34244. if (!effect) {
  34245. this._materialDefines = null;
  34246. }
  34247. return;
  34248. }
  34249. this._materialDefines = defines;
  34250. this._materialEffect = effect;
  34251. };
  34252. return BaseSubMesh;
  34253. }());
  34254. BABYLON.BaseSubMesh = BaseSubMesh;
  34255. var SubMesh = /** @class */ (function (_super) {
  34256. __extends(SubMesh, _super);
  34257. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34258. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34259. var _this = _super.call(this) || this;
  34260. _this.materialIndex = materialIndex;
  34261. _this.verticesStart = verticesStart;
  34262. _this.verticesCount = verticesCount;
  34263. _this.indexStart = indexStart;
  34264. _this.indexCount = indexCount;
  34265. _this._renderId = 0;
  34266. _this._mesh = mesh;
  34267. _this._renderingMesh = renderingMesh || mesh;
  34268. mesh.subMeshes.push(_this);
  34269. _this._trianglePlanes = [];
  34270. _this._id = mesh.subMeshes.length - 1;
  34271. if (createBoundingBox) {
  34272. _this.refreshBoundingInfo();
  34273. mesh.computeWorldMatrix(true);
  34274. }
  34275. return _this;
  34276. }
  34277. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34278. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34279. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34280. };
  34281. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34282. get: function () {
  34283. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34284. },
  34285. enumerable: true,
  34286. configurable: true
  34287. });
  34288. /**
  34289. * Returns the submesh BoudingInfo object.
  34290. */
  34291. SubMesh.prototype.getBoundingInfo = function () {
  34292. if (this.IsGlobal) {
  34293. return this._mesh.getBoundingInfo();
  34294. }
  34295. return this._boundingInfo;
  34296. };
  34297. /**
  34298. * Sets the submesh BoundingInfo.
  34299. * Return the SubMesh.
  34300. */
  34301. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34302. this._boundingInfo = boundingInfo;
  34303. return this;
  34304. };
  34305. /**
  34306. * Returns the mesh of the current submesh.
  34307. */
  34308. SubMesh.prototype.getMesh = function () {
  34309. return this._mesh;
  34310. };
  34311. /**
  34312. * Returns the rendering mesh of the submesh.
  34313. */
  34314. SubMesh.prototype.getRenderingMesh = function () {
  34315. return this._renderingMesh;
  34316. };
  34317. /**
  34318. * Returns the submesh material.
  34319. */
  34320. SubMesh.prototype.getMaterial = function () {
  34321. var rootMaterial = this._renderingMesh.material;
  34322. if (rootMaterial === null || rootMaterial === undefined) {
  34323. return this._mesh.getScene().defaultMaterial;
  34324. }
  34325. else if (rootMaterial.getSubMaterial) {
  34326. var multiMaterial = rootMaterial;
  34327. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34328. if (this._currentMaterial !== effectiveMaterial) {
  34329. this._currentMaterial = effectiveMaterial;
  34330. this._materialDefines = null;
  34331. }
  34332. return effectiveMaterial;
  34333. }
  34334. return rootMaterial;
  34335. };
  34336. // Methods
  34337. /**
  34338. * Sets a new updated BoundingInfo object to the submesh.
  34339. * Returns the SubMesh.
  34340. */
  34341. SubMesh.prototype.refreshBoundingInfo = function () {
  34342. this._lastColliderWorldVertices = null;
  34343. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34344. return this;
  34345. }
  34346. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34347. if (!data) {
  34348. this._boundingInfo = this._mesh.getBoundingInfo();
  34349. return this;
  34350. }
  34351. var indices = this._renderingMesh.getIndices();
  34352. var extend;
  34353. //is this the only submesh?
  34354. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34355. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34356. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34357. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34358. }
  34359. else {
  34360. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34361. }
  34362. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34363. return this;
  34364. };
  34365. SubMesh.prototype._checkCollision = function (collider) {
  34366. var boundingInfo = this.getBoundingInfo();
  34367. return boundingInfo._checkCollision(collider);
  34368. };
  34369. /**
  34370. * Updates the submesh BoundingInfo.
  34371. * Returns the Submesh.
  34372. */
  34373. SubMesh.prototype.updateBoundingInfo = function (world) {
  34374. var boundingInfo = this.getBoundingInfo();
  34375. if (!boundingInfo) {
  34376. this.refreshBoundingInfo();
  34377. boundingInfo = this.getBoundingInfo();
  34378. }
  34379. boundingInfo.update(world);
  34380. return this;
  34381. };
  34382. /**
  34383. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34384. * Boolean returned.
  34385. */
  34386. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34387. var boundingInfo = this.getBoundingInfo();
  34388. if (!boundingInfo) {
  34389. return false;
  34390. }
  34391. return boundingInfo.isInFrustum(frustumPlanes);
  34392. };
  34393. /**
  34394. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34395. * Boolean returned.
  34396. */
  34397. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34398. var boundingInfo = this.getBoundingInfo();
  34399. if (!boundingInfo) {
  34400. return false;
  34401. }
  34402. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34403. };
  34404. /**
  34405. * Renders the submesh.
  34406. * Returns it.
  34407. */
  34408. SubMesh.prototype.render = function (enableAlphaMode) {
  34409. this._renderingMesh.render(this, enableAlphaMode);
  34410. return this;
  34411. };
  34412. /**
  34413. * Returns a new Index Buffer.
  34414. * Type returned : WebGLBuffer.
  34415. */
  34416. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34417. if (!this._linesIndexBuffer) {
  34418. var linesIndices = [];
  34419. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34420. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34421. }
  34422. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34423. this.linesIndexCount = linesIndices.length;
  34424. }
  34425. return this._linesIndexBuffer;
  34426. };
  34427. /**
  34428. * True is the passed Ray intersects the submesh bounding box.
  34429. * Boolean returned.
  34430. */
  34431. SubMesh.prototype.canIntersects = function (ray) {
  34432. var boundingInfo = this.getBoundingInfo();
  34433. if (!boundingInfo) {
  34434. return false;
  34435. }
  34436. return ray.intersectsBox(boundingInfo.boundingBox);
  34437. };
  34438. /**
  34439. * Returns an object IntersectionInfo.
  34440. */
  34441. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34442. var intersectInfo = null;
  34443. var material = this.getMaterial();
  34444. if (!material) {
  34445. return null;
  34446. }
  34447. switch (material.fillMode) {
  34448. case BABYLON.Material.PointListDrawMode:
  34449. case BABYLON.Material.LineListDrawMode:
  34450. case BABYLON.Material.LineLoopDrawMode:
  34451. case BABYLON.Material.LineStripDrawMode:
  34452. case BABYLON.Material.TriangleFanDrawMode:
  34453. case BABYLON.Material.TriangleStripDrawMode:
  34454. return null;
  34455. }
  34456. // LineMesh first as it's also a Mesh...
  34457. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34458. var lineMesh = this._mesh;
  34459. // Line test
  34460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34461. var p0 = positions[indices[index]];
  34462. var p1 = positions[indices[index + 1]];
  34463. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34464. if (length < 0) {
  34465. continue;
  34466. }
  34467. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34468. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34469. if (fastCheck) {
  34470. break;
  34471. }
  34472. }
  34473. }
  34474. }
  34475. else {
  34476. // Triangles test
  34477. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34478. var p0 = positions[indices[index]];
  34479. var p1 = positions[indices[index + 1]];
  34480. var p2 = positions[indices[index + 2]];
  34481. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34482. if (currentIntersectInfo) {
  34483. if (currentIntersectInfo.distance < 0) {
  34484. continue;
  34485. }
  34486. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34487. intersectInfo = currentIntersectInfo;
  34488. intersectInfo.faceId = index / 3;
  34489. if (fastCheck) {
  34490. break;
  34491. }
  34492. }
  34493. }
  34494. }
  34495. }
  34496. return intersectInfo;
  34497. };
  34498. SubMesh.prototype._rebuild = function () {
  34499. if (this._linesIndexBuffer) {
  34500. this._linesIndexBuffer = null;
  34501. }
  34502. };
  34503. // Clone
  34504. /**
  34505. * Creates a new Submesh from the passed Mesh.
  34506. */
  34507. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34508. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34509. if (!this.IsGlobal) {
  34510. var boundingInfo = this.getBoundingInfo();
  34511. if (!boundingInfo) {
  34512. return result;
  34513. }
  34514. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34515. }
  34516. return result;
  34517. };
  34518. // Dispose
  34519. /**
  34520. * Disposes the Submesh.
  34521. * Returns nothing.
  34522. */
  34523. SubMesh.prototype.dispose = function () {
  34524. if (this._linesIndexBuffer) {
  34525. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34526. this._linesIndexBuffer = null;
  34527. }
  34528. // Remove from mesh
  34529. var index = this._mesh.subMeshes.indexOf(this);
  34530. this._mesh.subMeshes.splice(index, 1);
  34531. };
  34532. // Statics
  34533. /**
  34534. * Creates a new Submesh from the passed parameters :
  34535. * - materialIndex (integer) : the index of the main mesh material.
  34536. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34537. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34538. * - mesh (Mesh) : the main mesh to create the submesh from.
  34539. * - renderingMesh (optional Mesh) : rendering mesh.
  34540. */
  34541. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34542. var minVertexIndex = Number.MAX_VALUE;
  34543. var maxVertexIndex = -Number.MAX_VALUE;
  34544. renderingMesh = (renderingMesh || mesh);
  34545. var indices = renderingMesh.getIndices();
  34546. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34547. var vertexIndex = indices[index];
  34548. if (vertexIndex < minVertexIndex)
  34549. minVertexIndex = vertexIndex;
  34550. if (vertexIndex > maxVertexIndex)
  34551. maxVertexIndex = vertexIndex;
  34552. }
  34553. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34554. };
  34555. return SubMesh;
  34556. }(BaseSubMesh));
  34557. BABYLON.SubMesh = SubMesh;
  34558. })(BABYLON || (BABYLON = {}));
  34559. //# sourceMappingURL=babylon.subMesh.js.map
  34560. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34561. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34562. s = arguments[i];
  34563. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34564. t[p] = s[p];
  34565. }
  34566. return t;
  34567. };
  34568. var BABYLON;
  34569. (function (BABYLON) {
  34570. /**
  34571. * Manages the defines for the Material
  34572. */
  34573. var MaterialDefines = /** @class */ (function () {
  34574. function MaterialDefines() {
  34575. this._isDirty = true;
  34576. /** @hidden */
  34577. this._areLightsDirty = true;
  34578. /** @hidden */
  34579. this._areAttributesDirty = true;
  34580. /** @hidden */
  34581. this._areTexturesDirty = true;
  34582. /** @hidden */
  34583. this._areFresnelDirty = true;
  34584. /** @hidden */
  34585. this._areMiscDirty = true;
  34586. /** @hidden */
  34587. this._areImageProcessingDirty = true;
  34588. /** @hidden */
  34589. this._normals = false;
  34590. /** @hidden */
  34591. this._uvs = false;
  34592. /** @hidden */
  34593. this._needNormals = false;
  34594. /** @hidden */
  34595. this._needUVs = false;
  34596. }
  34597. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34598. /**
  34599. * Specifies if the material needs to be re-calculated
  34600. */
  34601. get: function () {
  34602. return this._isDirty;
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. /**
  34608. * Marks the material to indicate that it has been re-calculated
  34609. */
  34610. MaterialDefines.prototype.markAsProcessed = function () {
  34611. this._isDirty = false;
  34612. this._areAttributesDirty = false;
  34613. this._areTexturesDirty = false;
  34614. this._areFresnelDirty = false;
  34615. this._areLightsDirty = false;
  34616. this._areMiscDirty = false;
  34617. this._areImageProcessingDirty = false;
  34618. };
  34619. /**
  34620. * Marks the material to indicate that it needs to be re-calculated
  34621. */
  34622. MaterialDefines.prototype.markAsUnprocessed = function () {
  34623. this._isDirty = true;
  34624. };
  34625. /**
  34626. * Marks the material to indicate all of its defines need to be re-calculated
  34627. */
  34628. MaterialDefines.prototype.markAllAsDirty = function () {
  34629. this._areTexturesDirty = true;
  34630. this._areAttributesDirty = true;
  34631. this._areLightsDirty = true;
  34632. this._areFresnelDirty = true;
  34633. this._areMiscDirty = true;
  34634. this._areImageProcessingDirty = true;
  34635. this._isDirty = true;
  34636. };
  34637. /**
  34638. * Marks the material to indicate that image processing needs to be re-calculated
  34639. */
  34640. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34641. this._areImageProcessingDirty = true;
  34642. this._isDirty = true;
  34643. };
  34644. /**
  34645. * Marks the material to indicate the lights need to be re-calculated
  34646. */
  34647. MaterialDefines.prototype.markAsLightDirty = function () {
  34648. this._areLightsDirty = true;
  34649. this._isDirty = true;
  34650. };
  34651. /**
  34652. * Marks the attribute state as changed
  34653. */
  34654. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34655. this._areAttributesDirty = true;
  34656. this._isDirty = true;
  34657. };
  34658. /**
  34659. * Marks the texture state as changed
  34660. */
  34661. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34662. this._areTexturesDirty = true;
  34663. this._isDirty = true;
  34664. };
  34665. /**
  34666. * Marks the fresnel state as changed
  34667. */
  34668. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34669. this._areFresnelDirty = true;
  34670. this._isDirty = true;
  34671. };
  34672. /**
  34673. * Marks the misc state as changed
  34674. */
  34675. MaterialDefines.prototype.markAsMiscDirty = function () {
  34676. this._areMiscDirty = true;
  34677. this._isDirty = true;
  34678. };
  34679. /**
  34680. * Rebuilds the material defines
  34681. */
  34682. MaterialDefines.prototype.rebuild = function () {
  34683. if (this._keys) {
  34684. delete this._keys;
  34685. }
  34686. this._keys = [];
  34687. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34688. var key = _a[_i];
  34689. if (key[0] === "_") {
  34690. continue;
  34691. }
  34692. this._keys.push(key);
  34693. }
  34694. };
  34695. /**
  34696. * Specifies if two material defines are equal
  34697. * @param other - A material define instance to compare to
  34698. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34699. */
  34700. MaterialDefines.prototype.isEqual = function (other) {
  34701. if (this._keys.length !== other._keys.length) {
  34702. return false;
  34703. }
  34704. for (var index = 0; index < this._keys.length; index++) {
  34705. var prop = this._keys[index];
  34706. if (this[prop] !== other[prop]) {
  34707. return false;
  34708. }
  34709. }
  34710. return true;
  34711. };
  34712. /**
  34713. * Clones this instance's defines to another instance
  34714. * @param other - material defines to clone values to
  34715. */
  34716. MaterialDefines.prototype.cloneTo = function (other) {
  34717. if (this._keys.length !== other._keys.length) {
  34718. other._keys = this._keys.slice(0);
  34719. }
  34720. for (var index = 0; index < this._keys.length; index++) {
  34721. var prop = this._keys[index];
  34722. other[prop] = this[prop];
  34723. }
  34724. };
  34725. /**
  34726. * Resets the material define values
  34727. */
  34728. MaterialDefines.prototype.reset = function () {
  34729. for (var index = 0; index < this._keys.length; index++) {
  34730. var prop = this._keys[index];
  34731. var type = typeof this[prop];
  34732. switch (type) {
  34733. case "number":
  34734. this[prop] = 0;
  34735. break;
  34736. case "string":
  34737. this[prop] = "";
  34738. break;
  34739. default:
  34740. this[prop] = false;
  34741. break;
  34742. }
  34743. }
  34744. };
  34745. /**
  34746. * Converts the material define values to a string
  34747. * @returns - String of material define information
  34748. */
  34749. MaterialDefines.prototype.toString = function () {
  34750. var result = "";
  34751. for (var index = 0; index < this._keys.length; index++) {
  34752. var prop = this._keys[index];
  34753. var value = this[prop];
  34754. var type = typeof value;
  34755. switch (type) {
  34756. case "number":
  34757. case "string":
  34758. result += "#define " + prop + " " + value + "\n";
  34759. break;
  34760. default:
  34761. if (value) {
  34762. result += "#define " + prop + "\n";
  34763. }
  34764. break;
  34765. }
  34766. }
  34767. return result;
  34768. };
  34769. return MaterialDefines;
  34770. }());
  34771. BABYLON.MaterialDefines = MaterialDefines;
  34772. /**
  34773. * Base class for the main features of a material in Babylon.js
  34774. */
  34775. var Material = /** @class */ (function () {
  34776. /**
  34777. * Creates a material instance
  34778. * @param name defines the name of the material
  34779. * @param scene defines the scene to reference
  34780. * @param doNotAdd specifies if the material should be added to the scene
  34781. */
  34782. function Material(name, scene, doNotAdd) {
  34783. /**
  34784. * Specifies if the ready state should be checked on each call
  34785. */
  34786. this.checkReadyOnEveryCall = false;
  34787. /**
  34788. * Specifies if the ready state should be checked once
  34789. */
  34790. this.checkReadyOnlyOnce = false;
  34791. /**
  34792. * The state of the material
  34793. */
  34794. this.state = "";
  34795. /**
  34796. * The alpha value of the material
  34797. */
  34798. this._alpha = 1.0;
  34799. /**
  34800. * Specifies if back face culling is enabled
  34801. */
  34802. this._backFaceCulling = true;
  34803. /**
  34804. * Specifies if the material should be serialized
  34805. */
  34806. this.doNotSerialize = false;
  34807. /**
  34808. * Specifies if the effect should be stored on sub meshes
  34809. */
  34810. this.storeEffectOnSubMeshes = false;
  34811. /**
  34812. * An event triggered when the material is disposed
  34813. */
  34814. this.onDisposeObservable = new BABYLON.Observable();
  34815. /**
  34816. * An event triggered when the material is bound
  34817. */
  34818. this.onBindObservable = new BABYLON.Observable();
  34819. /**
  34820. * An event triggered when the material is unbound
  34821. */
  34822. this.onUnBindObservable = new BABYLON.Observable();
  34823. /**
  34824. * Stores the value of the alpha mode
  34825. */
  34826. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34827. /**
  34828. * Stores the state of the need depth pre-pass value
  34829. */
  34830. this._needDepthPrePass = false;
  34831. /**
  34832. * Specifies if depth writing should be disabled
  34833. */
  34834. this.disableDepthWrite = false;
  34835. /**
  34836. * Specifies if depth writing should be forced
  34837. */
  34838. this.forceDepthWrite = false;
  34839. /**
  34840. * Specifies if there should be a separate pass for culling
  34841. */
  34842. this.separateCullingPass = false;
  34843. /**
  34844. * Stores the state specifing if fog should be enabled
  34845. */
  34846. this._fogEnabled = true;
  34847. /**
  34848. * Stores the size of points
  34849. */
  34850. this.pointSize = 1.0;
  34851. /**
  34852. * Stores the z offset value
  34853. */
  34854. this.zOffset = 0;
  34855. /**
  34856. * Specifies if the material was previously ready
  34857. */
  34858. this._wasPreviouslyReady = false;
  34859. /**
  34860. * Stores the fill mode state
  34861. */
  34862. this._fillMode = Material.TriangleFillMode;
  34863. this.name = name;
  34864. this.id = name || BABYLON.Tools.RandomId();
  34865. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34866. this.uniqueId = this._scene.getUniqueId();
  34867. if (this._scene.useRightHandedSystem) {
  34868. this.sideOrientation = Material.ClockWiseSideOrientation;
  34869. }
  34870. else {
  34871. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34872. }
  34873. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34874. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34875. if (!doNotAdd) {
  34876. this._scene.materials.push(this);
  34877. }
  34878. }
  34879. Object.defineProperty(Material, "TriangleFillMode", {
  34880. /**
  34881. * Returns the triangle fill mode
  34882. */
  34883. get: function () {
  34884. return Material._TriangleFillMode;
  34885. },
  34886. enumerable: true,
  34887. configurable: true
  34888. });
  34889. Object.defineProperty(Material, "WireFrameFillMode", {
  34890. /**
  34891. * Returns the wireframe mode
  34892. */
  34893. get: function () {
  34894. return Material._WireFrameFillMode;
  34895. },
  34896. enumerable: true,
  34897. configurable: true
  34898. });
  34899. Object.defineProperty(Material, "PointFillMode", {
  34900. /**
  34901. * Returns the point fill mode
  34902. */
  34903. get: function () {
  34904. return Material._PointFillMode;
  34905. },
  34906. enumerable: true,
  34907. configurable: true
  34908. });
  34909. Object.defineProperty(Material, "PointListDrawMode", {
  34910. /**
  34911. * Returns the point list draw mode
  34912. */
  34913. get: function () {
  34914. return Material._PointListDrawMode;
  34915. },
  34916. enumerable: true,
  34917. configurable: true
  34918. });
  34919. Object.defineProperty(Material, "LineListDrawMode", {
  34920. /**
  34921. * Returns the line list draw mode
  34922. */
  34923. get: function () {
  34924. return Material._LineListDrawMode;
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. Object.defineProperty(Material, "LineLoopDrawMode", {
  34930. /**
  34931. * Returns the line loop draw mode
  34932. */
  34933. get: function () {
  34934. return Material._LineLoopDrawMode;
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. Object.defineProperty(Material, "LineStripDrawMode", {
  34940. /**
  34941. * Returns the line strip draw mode
  34942. */
  34943. get: function () {
  34944. return Material._LineStripDrawMode;
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34950. /**
  34951. * Returns the triangle strip draw mode
  34952. */
  34953. get: function () {
  34954. return Material._TriangleStripDrawMode;
  34955. },
  34956. enumerable: true,
  34957. configurable: true
  34958. });
  34959. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34960. /**
  34961. * Returns the triangle fan draw mode
  34962. */
  34963. get: function () {
  34964. return Material._TriangleFanDrawMode;
  34965. },
  34966. enumerable: true,
  34967. configurable: true
  34968. });
  34969. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34970. /**
  34971. * Returns the clock-wise side orientation
  34972. */
  34973. get: function () {
  34974. return Material._ClockWiseSideOrientation;
  34975. },
  34976. enumerable: true,
  34977. configurable: true
  34978. });
  34979. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34980. /**
  34981. * Returns the counter clock-wise side orientation
  34982. */
  34983. get: function () {
  34984. return Material._CounterClockWiseSideOrientation;
  34985. },
  34986. enumerable: true,
  34987. configurable: true
  34988. });
  34989. Object.defineProperty(Material, "TextureDirtyFlag", {
  34990. /**
  34991. * Returns the dirty texture flag value
  34992. */
  34993. get: function () {
  34994. return Material._TextureDirtyFlag;
  34995. },
  34996. enumerable: true,
  34997. configurable: true
  34998. });
  34999. Object.defineProperty(Material, "LightDirtyFlag", {
  35000. /**
  35001. * Returns the dirty light flag value
  35002. */
  35003. get: function () {
  35004. return Material._LightDirtyFlag;
  35005. },
  35006. enumerable: true,
  35007. configurable: true
  35008. });
  35009. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35010. /**
  35011. * Returns the dirty fresnel flag value
  35012. */
  35013. get: function () {
  35014. return Material._FresnelDirtyFlag;
  35015. },
  35016. enumerable: true,
  35017. configurable: true
  35018. });
  35019. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35020. /**
  35021. * Returns the dirty attributes flag value
  35022. */
  35023. get: function () {
  35024. return Material._AttributesDirtyFlag;
  35025. },
  35026. enumerable: true,
  35027. configurable: true
  35028. });
  35029. Object.defineProperty(Material, "MiscDirtyFlag", {
  35030. /**
  35031. * Returns the dirty misc flag value
  35032. */
  35033. get: function () {
  35034. return Material._MiscDirtyFlag;
  35035. },
  35036. enumerable: true,
  35037. configurable: true
  35038. });
  35039. Object.defineProperty(Material.prototype, "alpha", {
  35040. /**
  35041. * Gets the alpha value of the material
  35042. */
  35043. get: function () {
  35044. return this._alpha;
  35045. },
  35046. /**
  35047. * Sets the alpha value of the material
  35048. */
  35049. set: function (value) {
  35050. if (this._alpha === value) {
  35051. return;
  35052. }
  35053. this._alpha = value;
  35054. this.markAsDirty(Material.MiscDirtyFlag);
  35055. },
  35056. enumerable: true,
  35057. configurable: true
  35058. });
  35059. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35060. /**
  35061. * Gets the back-face culling state
  35062. */
  35063. get: function () {
  35064. return this._backFaceCulling;
  35065. },
  35066. /**
  35067. * Sets the back-face culling state
  35068. */
  35069. set: function (value) {
  35070. if (this._backFaceCulling === value) {
  35071. return;
  35072. }
  35073. this._backFaceCulling = value;
  35074. this.markAsDirty(Material.TextureDirtyFlag);
  35075. },
  35076. enumerable: true,
  35077. configurable: true
  35078. });
  35079. Object.defineProperty(Material.prototype, "onDispose", {
  35080. /**
  35081. * Called during a dispose event
  35082. */
  35083. set: function (callback) {
  35084. if (this._onDisposeObserver) {
  35085. this.onDisposeObservable.remove(this._onDisposeObserver);
  35086. }
  35087. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35088. },
  35089. enumerable: true,
  35090. configurable: true
  35091. });
  35092. Object.defineProperty(Material.prototype, "onBind", {
  35093. /**
  35094. * Called during a bind event
  35095. */
  35096. set: function (callback) {
  35097. if (this._onBindObserver) {
  35098. this.onBindObservable.remove(this._onBindObserver);
  35099. }
  35100. this._onBindObserver = this.onBindObservable.add(callback);
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. Object.defineProperty(Material.prototype, "alphaMode", {
  35106. /**
  35107. * Gets the value of the alpha mode
  35108. */
  35109. get: function () {
  35110. return this._alphaMode;
  35111. },
  35112. /**
  35113. * Sets the value of the alpha mode.
  35114. *
  35115. * | Value | Type | Description |
  35116. * | --- | --- | --- |
  35117. * | 0 | ALPHA_DISABLE | |
  35118. * | 1 | ALPHA_ADD | |
  35119. * | 2 | ALPHA_COMBINE | |
  35120. * | 3 | ALPHA_SUBTRACT | |
  35121. * | 4 | ALPHA_MULTIPLY | |
  35122. * | 5 | ALPHA_MAXIMIZED | |
  35123. * | 6 | ALPHA_ONEONE | |
  35124. * | 7 | ALPHA_PREMULTIPLIED | |
  35125. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35126. * | 9 | ALPHA_INTERPOLATE | |
  35127. * | 10 | ALPHA_SCREENMODE | |
  35128. *
  35129. */
  35130. set: function (value) {
  35131. if (this._alphaMode === value) {
  35132. return;
  35133. }
  35134. this._alphaMode = value;
  35135. this.markAsDirty(Material.TextureDirtyFlag);
  35136. },
  35137. enumerable: true,
  35138. configurable: true
  35139. });
  35140. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35141. /**
  35142. * Gets the depth pre-pass value
  35143. */
  35144. get: function () {
  35145. return this._needDepthPrePass;
  35146. },
  35147. /**
  35148. * Sets the need depth pre-pass value
  35149. */
  35150. set: function (value) {
  35151. if (this._needDepthPrePass === value) {
  35152. return;
  35153. }
  35154. this._needDepthPrePass = value;
  35155. if (this._needDepthPrePass) {
  35156. this.checkReadyOnEveryCall = true;
  35157. }
  35158. },
  35159. enumerable: true,
  35160. configurable: true
  35161. });
  35162. Object.defineProperty(Material.prototype, "fogEnabled", {
  35163. /**
  35164. * Gets the value of the fog enabled state
  35165. */
  35166. get: function () {
  35167. return this._fogEnabled;
  35168. },
  35169. /**
  35170. * Sets the state for enabling fog
  35171. */
  35172. set: function (value) {
  35173. if (this._fogEnabled === value) {
  35174. return;
  35175. }
  35176. this._fogEnabled = value;
  35177. this.markAsDirty(Material.MiscDirtyFlag);
  35178. },
  35179. enumerable: true,
  35180. configurable: true
  35181. });
  35182. Object.defineProperty(Material.prototype, "wireframe", {
  35183. /**
  35184. * Gets a value specifying if wireframe mode is enabled
  35185. */
  35186. get: function () {
  35187. switch (this._fillMode) {
  35188. case Material.WireFrameFillMode:
  35189. case Material.LineListDrawMode:
  35190. case Material.LineLoopDrawMode:
  35191. case Material.LineStripDrawMode:
  35192. return true;
  35193. }
  35194. return this._scene.forceWireframe;
  35195. },
  35196. /**
  35197. * Sets the state of wireframe mode
  35198. */
  35199. set: function (value) {
  35200. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35201. },
  35202. enumerable: true,
  35203. configurable: true
  35204. });
  35205. Object.defineProperty(Material.prototype, "pointsCloud", {
  35206. /**
  35207. * Gets the value specifying if point clouds are enabled
  35208. */
  35209. get: function () {
  35210. switch (this._fillMode) {
  35211. case Material.PointFillMode:
  35212. case Material.PointListDrawMode:
  35213. return true;
  35214. }
  35215. return this._scene.forcePointsCloud;
  35216. },
  35217. /**
  35218. * Sets the state of point cloud mode
  35219. */
  35220. set: function (value) {
  35221. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(Material.prototype, "fillMode", {
  35227. /**
  35228. * Gets the material fill mode
  35229. */
  35230. get: function () {
  35231. return this._fillMode;
  35232. },
  35233. /**
  35234. * Sets the material fill mode
  35235. */
  35236. set: function (value) {
  35237. if (this._fillMode === value) {
  35238. return;
  35239. }
  35240. this._fillMode = value;
  35241. this.markAsDirty(Material.MiscDirtyFlag);
  35242. },
  35243. enumerable: true,
  35244. configurable: true
  35245. });
  35246. /**
  35247. * Returns a string representation of the current material
  35248. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35249. * @returns a string with material information
  35250. */
  35251. Material.prototype.toString = function (fullDetails) {
  35252. var ret = "Name: " + this.name;
  35253. if (fullDetails) {
  35254. }
  35255. return ret;
  35256. };
  35257. /**
  35258. * Gets the class name of the material
  35259. * @returns a string with the class name of the material
  35260. */
  35261. Material.prototype.getClassName = function () {
  35262. return "Material";
  35263. };
  35264. Object.defineProperty(Material.prototype, "isFrozen", {
  35265. /**
  35266. * Specifies if updates for the material been locked
  35267. */
  35268. get: function () {
  35269. return this.checkReadyOnlyOnce;
  35270. },
  35271. enumerable: true,
  35272. configurable: true
  35273. });
  35274. /**
  35275. * Locks updates for the material
  35276. */
  35277. Material.prototype.freeze = function () {
  35278. this.checkReadyOnlyOnce = true;
  35279. };
  35280. /**
  35281. * Unlocks updates for the material
  35282. */
  35283. Material.prototype.unfreeze = function () {
  35284. this.checkReadyOnlyOnce = false;
  35285. };
  35286. /**
  35287. * Specifies if the material is ready to be used
  35288. * @param mesh defines the mesh to check
  35289. * @param useInstances specifies if instances should be used
  35290. * @returns a boolean indicating if the material is ready to be used
  35291. */
  35292. Material.prototype.isReady = function (mesh, useInstances) {
  35293. return true;
  35294. };
  35295. /**
  35296. * Specifies that the submesh is ready to be used
  35297. * @param mesh defines the mesh to check
  35298. * @param subMesh defines which submesh to check
  35299. * @param useInstances specifies that instances should be used
  35300. * @returns a boolean indicating that the submesh is ready or not
  35301. */
  35302. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35303. return false;
  35304. };
  35305. /**
  35306. * Returns the material effect
  35307. * @returns the effect associated with the material
  35308. */
  35309. Material.prototype.getEffect = function () {
  35310. return this._effect;
  35311. };
  35312. /**
  35313. * Returns the current scene
  35314. * @returns a Scene
  35315. */
  35316. Material.prototype.getScene = function () {
  35317. return this._scene;
  35318. };
  35319. /**
  35320. * Specifies if the material will require alpha blending
  35321. * @returns a boolean specifying if alpha blending is needed
  35322. */
  35323. Material.prototype.needAlphaBlending = function () {
  35324. return (this.alpha < 1.0);
  35325. };
  35326. /**
  35327. * Specifies if the mesh will require alpha blending
  35328. * @param mesh defines the mesh to check
  35329. * @returns a boolean specifying if alpha blending is needed for the mesh
  35330. */
  35331. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35332. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35333. };
  35334. /**
  35335. * Specifies if this material should be rendered in alpha test mode
  35336. * @returns a boolean specifying if an alpha test is needed.
  35337. */
  35338. Material.prototype.needAlphaTesting = function () {
  35339. return false;
  35340. };
  35341. /**
  35342. * Gets the texture used for the alpha test
  35343. * @returns the texture to use for alpha testing
  35344. */
  35345. Material.prototype.getAlphaTestTexture = function () {
  35346. return null;
  35347. };
  35348. /**
  35349. * Marks the material to indicate that it needs to be re-calculated
  35350. */
  35351. Material.prototype.markDirty = function () {
  35352. this._wasPreviouslyReady = false;
  35353. };
  35354. /** @hidden */
  35355. Material.prototype._preBind = function (effect, overrideOrientation) {
  35356. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35357. var engine = this._scene.getEngine();
  35358. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35359. var reverse = orientation === Material.ClockWiseSideOrientation;
  35360. engine.enableEffect(effect ? effect : this._effect);
  35361. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35362. return reverse;
  35363. };
  35364. /**
  35365. * Binds the material to the mesh
  35366. * @param world defines the world transformation matrix
  35367. * @param mesh defines the mesh to bind the material to
  35368. */
  35369. Material.prototype.bind = function (world, mesh) {
  35370. };
  35371. /**
  35372. * Binds the submesh to the material
  35373. * @param world defines the world transformation matrix
  35374. * @param mesh defines the mesh containing the submesh
  35375. * @param subMesh defines the submesh to bind the material to
  35376. */
  35377. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35378. };
  35379. /**
  35380. * Binds the world matrix to the material
  35381. * @param world defines the world transformation matrix
  35382. */
  35383. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35384. };
  35385. /**
  35386. * Binds the scene's uniform buffer to the effect.
  35387. * @param effect defines the effect to bind to the scene uniform buffer
  35388. * @param sceneUbo defines the uniform buffer storing scene data
  35389. */
  35390. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35391. sceneUbo.bindToEffect(effect, "Scene");
  35392. };
  35393. /**
  35394. * Binds the view matrix to the effect
  35395. * @param effect defines the effect to bind the view matrix to
  35396. */
  35397. Material.prototype.bindView = function (effect) {
  35398. if (!this._useUBO) {
  35399. effect.setMatrix("view", this.getScene().getViewMatrix());
  35400. }
  35401. else {
  35402. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35403. }
  35404. };
  35405. /**
  35406. * Binds the view projection matrix to the effect
  35407. * @param effect defines the effect to bind the view projection matrix to
  35408. */
  35409. Material.prototype.bindViewProjection = function (effect) {
  35410. if (!this._useUBO) {
  35411. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35412. }
  35413. else {
  35414. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35415. }
  35416. };
  35417. /**
  35418. * Specifies if material alpha testing should be turned on for the mesh
  35419. * @param mesh defines the mesh to check
  35420. */
  35421. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35422. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35423. };
  35424. /**
  35425. * Processes to execute after binding the material to a mesh
  35426. * @param mesh defines the rendered mesh
  35427. */
  35428. Material.prototype._afterBind = function (mesh) {
  35429. this._scene._cachedMaterial = this;
  35430. if (mesh) {
  35431. this._scene._cachedVisibility = mesh.visibility;
  35432. }
  35433. else {
  35434. this._scene._cachedVisibility = 1;
  35435. }
  35436. if (mesh) {
  35437. this.onBindObservable.notifyObservers(mesh);
  35438. }
  35439. if (this.disableDepthWrite) {
  35440. var engine = this._scene.getEngine();
  35441. this._cachedDepthWriteState = engine.getDepthWrite();
  35442. engine.setDepthWrite(false);
  35443. }
  35444. };
  35445. /**
  35446. * Unbinds the material from the mesh
  35447. */
  35448. Material.prototype.unbind = function () {
  35449. this.onUnBindObservable.notifyObservers(this);
  35450. if (this.disableDepthWrite) {
  35451. var engine = this._scene.getEngine();
  35452. engine.setDepthWrite(this._cachedDepthWriteState);
  35453. }
  35454. };
  35455. /**
  35456. * Gets the active textures from the material
  35457. * @returns an array of textures
  35458. */
  35459. Material.prototype.getActiveTextures = function () {
  35460. return [];
  35461. };
  35462. /**
  35463. * Specifies if the material uses a texture
  35464. * @param texture defines the texture to check against the material
  35465. * @returns a boolean specifying if the material uses the texture
  35466. */
  35467. Material.prototype.hasTexture = function (texture) {
  35468. return false;
  35469. };
  35470. /**
  35471. * Makes a duplicate of the material, and gives it a new name
  35472. * @param name defines the new name for the duplicated material
  35473. * @returns the cloned material
  35474. */
  35475. Material.prototype.clone = function (name) {
  35476. return null;
  35477. };
  35478. /**
  35479. * Gets the meshes bound to the material
  35480. * @returns an array of meshes bound to the material
  35481. */
  35482. Material.prototype.getBindedMeshes = function () {
  35483. var result = new Array();
  35484. for (var index = 0; index < this._scene.meshes.length; index++) {
  35485. var mesh = this._scene.meshes[index];
  35486. if (mesh.material === this) {
  35487. result.push(mesh);
  35488. }
  35489. }
  35490. return result;
  35491. };
  35492. /**
  35493. * Force shader compilation
  35494. * @param mesh defines the mesh associated with this material
  35495. * @param onCompiled defines a function to execute once the material is compiled
  35496. * @param options defines the options to configure the compilation
  35497. */
  35498. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35499. var _this = this;
  35500. var localOptions = __assign({ clipPlane: false }, options);
  35501. var subMesh = new BABYLON.BaseSubMesh();
  35502. var scene = this.getScene();
  35503. var checkReady = function () {
  35504. if (!_this._scene || !_this._scene.getEngine()) {
  35505. return;
  35506. }
  35507. if (subMesh._materialDefines) {
  35508. subMesh._materialDefines._renderId = -1;
  35509. }
  35510. var clipPlaneState = scene.clipPlane;
  35511. if (localOptions.clipPlane) {
  35512. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35513. }
  35514. if (_this.storeEffectOnSubMeshes) {
  35515. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35516. if (onCompiled) {
  35517. onCompiled(_this);
  35518. }
  35519. }
  35520. else {
  35521. setTimeout(checkReady, 16);
  35522. }
  35523. }
  35524. else {
  35525. if (_this.isReady(mesh)) {
  35526. if (onCompiled) {
  35527. onCompiled(_this);
  35528. }
  35529. }
  35530. else {
  35531. setTimeout(checkReady, 16);
  35532. }
  35533. }
  35534. if (localOptions.clipPlane) {
  35535. scene.clipPlane = clipPlaneState;
  35536. }
  35537. };
  35538. checkReady();
  35539. };
  35540. /**
  35541. * Force shader compilation
  35542. * @param mesh defines the mesh that will use this material
  35543. * @param options defines additional options for compiling the shaders
  35544. * @returns a promise that resolves when the compilation completes
  35545. */
  35546. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35547. var _this = this;
  35548. return new Promise(function (resolve) {
  35549. _this.forceCompilation(mesh, function () {
  35550. resolve();
  35551. }, options);
  35552. });
  35553. };
  35554. /**
  35555. * Marks a define in the material to indicate that it needs to be re-computed
  35556. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35557. */
  35558. Material.prototype.markAsDirty = function (flag) {
  35559. if (flag & Material.TextureDirtyFlag) {
  35560. this._markAllSubMeshesAsTexturesDirty();
  35561. }
  35562. if (flag & Material.LightDirtyFlag) {
  35563. this._markAllSubMeshesAsLightsDirty();
  35564. }
  35565. if (flag & Material.FresnelDirtyFlag) {
  35566. this._markAllSubMeshesAsFresnelDirty();
  35567. }
  35568. if (flag & Material.AttributesDirtyFlag) {
  35569. this._markAllSubMeshesAsAttributesDirty();
  35570. }
  35571. if (flag & Material.MiscDirtyFlag) {
  35572. this._markAllSubMeshesAsMiscDirty();
  35573. }
  35574. this.getScene().resetCachedMaterial();
  35575. };
  35576. /**
  35577. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35578. * @param func defines a function which checks material defines against the submeshes
  35579. */
  35580. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35581. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35582. var mesh = _a[_i];
  35583. if (!mesh.subMeshes) {
  35584. continue;
  35585. }
  35586. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35587. var subMesh = _c[_b];
  35588. if (subMesh.getMaterial() !== this) {
  35589. continue;
  35590. }
  35591. if (!subMesh._materialDefines) {
  35592. continue;
  35593. }
  35594. func(subMesh._materialDefines);
  35595. }
  35596. }
  35597. };
  35598. /**
  35599. * Indicates that image processing needs to be re-calculated for all submeshes
  35600. */
  35601. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35602. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35603. };
  35604. /**
  35605. * Indicates that textures need to be re-calculated for all submeshes
  35606. */
  35607. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35608. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35609. };
  35610. /**
  35611. * Indicates that fresnel needs to be re-calculated for all submeshes
  35612. */
  35613. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35614. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35615. };
  35616. /**
  35617. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35618. */
  35619. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35620. this._markAllSubMeshesAsDirty(function (defines) {
  35621. defines.markAsFresnelDirty();
  35622. defines.markAsMiscDirty();
  35623. });
  35624. };
  35625. /**
  35626. * Indicates that lights need to be re-calculated for all submeshes
  35627. */
  35628. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35629. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35630. };
  35631. /**
  35632. * Indicates that attributes need to be re-calculated for all submeshes
  35633. */
  35634. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35635. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35636. };
  35637. /**
  35638. * Indicates that misc needs to be re-calculated for all submeshes
  35639. */
  35640. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35641. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35642. };
  35643. /**
  35644. * Indicates that textures and misc need to be re-calculated for all submeshes
  35645. */
  35646. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35647. this._markAllSubMeshesAsDirty(function (defines) {
  35648. defines.markAsTexturesDirty();
  35649. defines.markAsMiscDirty();
  35650. });
  35651. };
  35652. /**
  35653. * Disposes the material
  35654. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35655. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35656. */
  35657. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35658. // Animations
  35659. this.getScene().stopAnimation(this);
  35660. this.getScene().freeProcessedMaterials();
  35661. // Remove from scene
  35662. var index = this._scene.materials.indexOf(this);
  35663. if (index >= 0) {
  35664. this._scene.materials.splice(index, 1);
  35665. }
  35666. // Remove from meshes
  35667. for (index = 0; index < this._scene.meshes.length; index++) {
  35668. var mesh = this._scene.meshes[index];
  35669. if (mesh.material === this) {
  35670. mesh.material = null;
  35671. if (mesh.geometry) {
  35672. var geometry = (mesh.geometry);
  35673. if (this.storeEffectOnSubMeshes) {
  35674. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35675. var subMesh = _a[_i];
  35676. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35677. if (forceDisposeEffect && subMesh._materialEffect) {
  35678. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35679. }
  35680. }
  35681. }
  35682. else {
  35683. geometry._releaseVertexArrayObject(this._effect);
  35684. }
  35685. }
  35686. }
  35687. }
  35688. this._uniformBuffer.dispose();
  35689. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35690. if (forceDisposeEffect && this._effect) {
  35691. if (!this.storeEffectOnSubMeshes) {
  35692. this._scene.getEngine()._releaseEffect(this._effect);
  35693. }
  35694. this._effect = null;
  35695. }
  35696. // Callback
  35697. this.onDisposeObservable.notifyObservers(this);
  35698. this.onDisposeObservable.clear();
  35699. this.onBindObservable.clear();
  35700. this.onUnBindObservable.clear();
  35701. };
  35702. /**
  35703. * Serializes this material
  35704. * @returns the serialized material object
  35705. */
  35706. Material.prototype.serialize = function () {
  35707. return BABYLON.SerializationHelper.Serialize(this);
  35708. };
  35709. /**
  35710. * Creates a MultiMaterial from parsed MultiMaterial data.
  35711. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35712. * @param scene defines the hosting scene
  35713. * @returns a new MultiMaterial
  35714. */
  35715. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35716. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35717. multiMaterial.id = parsedMultiMaterial.id;
  35718. if (BABYLON.Tags) {
  35719. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35720. }
  35721. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35722. var subMatId = parsedMultiMaterial.materials[matIndex];
  35723. if (subMatId) {
  35724. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35725. }
  35726. else {
  35727. multiMaterial.subMaterials.push(null);
  35728. }
  35729. }
  35730. return multiMaterial;
  35731. };
  35732. /**
  35733. * Creates a material from parsed material data
  35734. * @param parsedMaterial defines parsed material data
  35735. * @param scene defines the hosting scene
  35736. * @param rootUrl defines the root URL to use to load textures
  35737. * @returns a new material
  35738. */
  35739. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35740. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35741. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35742. }
  35743. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35744. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35745. if (!BABYLON.LegacyPBRMaterial) {
  35746. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35747. return;
  35748. }
  35749. }
  35750. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35751. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35752. };
  35753. // Triangle views
  35754. Material._TriangleFillMode = 0;
  35755. Material._WireFrameFillMode = 1;
  35756. Material._PointFillMode = 2;
  35757. // Draw modes
  35758. Material._PointListDrawMode = 3;
  35759. Material._LineListDrawMode = 4;
  35760. Material._LineLoopDrawMode = 5;
  35761. Material._LineStripDrawMode = 6;
  35762. Material._TriangleStripDrawMode = 7;
  35763. Material._TriangleFanDrawMode = 8;
  35764. /**
  35765. * Stores the clock-wise side orientation
  35766. */
  35767. Material._ClockWiseSideOrientation = 0;
  35768. /**
  35769. * Stores the counter clock-wise side orientation
  35770. */
  35771. Material._CounterClockWiseSideOrientation = 1;
  35772. /**
  35773. * The dirty texture flag value
  35774. */
  35775. Material._TextureDirtyFlag = 1;
  35776. /**
  35777. * The dirty light flag value
  35778. */
  35779. Material._LightDirtyFlag = 2;
  35780. /**
  35781. * The dirty fresnel flag value
  35782. */
  35783. Material._FresnelDirtyFlag = 4;
  35784. /**
  35785. * The dirty attribute flag value
  35786. */
  35787. Material._AttributesDirtyFlag = 8;
  35788. /**
  35789. * The dirty misc flag value
  35790. */
  35791. Material._MiscDirtyFlag = 16;
  35792. __decorate([
  35793. BABYLON.serialize()
  35794. ], Material.prototype, "id", void 0);
  35795. __decorate([
  35796. BABYLON.serialize()
  35797. ], Material.prototype, "uniqueId", void 0);
  35798. __decorate([
  35799. BABYLON.serialize()
  35800. ], Material.prototype, "name", void 0);
  35801. __decorate([
  35802. BABYLON.serialize()
  35803. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35804. __decorate([
  35805. BABYLON.serialize()
  35806. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35807. __decorate([
  35808. BABYLON.serialize()
  35809. ], Material.prototype, "state", void 0);
  35810. __decorate([
  35811. BABYLON.serialize("alpha")
  35812. ], Material.prototype, "_alpha", void 0);
  35813. __decorate([
  35814. BABYLON.serialize("backFaceCulling")
  35815. ], Material.prototype, "_backFaceCulling", void 0);
  35816. __decorate([
  35817. BABYLON.serialize()
  35818. ], Material.prototype, "sideOrientation", void 0);
  35819. __decorate([
  35820. BABYLON.serialize("alphaMode")
  35821. ], Material.prototype, "_alphaMode", void 0);
  35822. __decorate([
  35823. BABYLON.serialize()
  35824. ], Material.prototype, "_needDepthPrePass", void 0);
  35825. __decorate([
  35826. BABYLON.serialize()
  35827. ], Material.prototype, "disableDepthWrite", void 0);
  35828. __decorate([
  35829. BABYLON.serialize()
  35830. ], Material.prototype, "forceDepthWrite", void 0);
  35831. __decorate([
  35832. BABYLON.serialize()
  35833. ], Material.prototype, "separateCullingPass", void 0);
  35834. __decorate([
  35835. BABYLON.serialize("fogEnabled")
  35836. ], Material.prototype, "_fogEnabled", void 0);
  35837. __decorate([
  35838. BABYLON.serialize()
  35839. ], Material.prototype, "pointSize", void 0);
  35840. __decorate([
  35841. BABYLON.serialize()
  35842. ], Material.prototype, "zOffset", void 0);
  35843. __decorate([
  35844. BABYLON.serialize()
  35845. ], Material.prototype, "wireframe", null);
  35846. __decorate([
  35847. BABYLON.serialize()
  35848. ], Material.prototype, "pointsCloud", null);
  35849. __decorate([
  35850. BABYLON.serialize()
  35851. ], Material.prototype, "fillMode", null);
  35852. return Material;
  35853. }());
  35854. BABYLON.Material = Material;
  35855. })(BABYLON || (BABYLON = {}));
  35856. //# sourceMappingURL=babylon.material.js.map
  35857. var BABYLON;
  35858. (function (BABYLON) {
  35859. var UniformBuffer = /** @class */ (function () {
  35860. /**
  35861. * Uniform buffer objects.
  35862. *
  35863. * Handles blocks of uniform on the GPU.
  35864. *
  35865. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35866. *
  35867. * For more information, please refer to :
  35868. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35869. */
  35870. function UniformBuffer(engine, data, dynamic) {
  35871. this._engine = engine;
  35872. this._noUBO = !engine.supportsUniformBuffers;
  35873. this._dynamic = dynamic;
  35874. this._data = data || [];
  35875. this._uniformLocations = {};
  35876. this._uniformSizes = {};
  35877. this._uniformLocationPointer = 0;
  35878. this._needSync = false;
  35879. if (this._noUBO) {
  35880. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35881. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35882. this.updateFloat = this._updateFloatForEffect;
  35883. this.updateFloat2 = this._updateFloat2ForEffect;
  35884. this.updateFloat3 = this._updateFloat3ForEffect;
  35885. this.updateFloat4 = this._updateFloat4ForEffect;
  35886. this.updateMatrix = this._updateMatrixForEffect;
  35887. this.updateVector3 = this._updateVector3ForEffect;
  35888. this.updateVector4 = this._updateVector4ForEffect;
  35889. this.updateColor3 = this._updateColor3ForEffect;
  35890. this.updateColor4 = this._updateColor4ForEffect;
  35891. }
  35892. else {
  35893. this._engine._uniformBuffers.push(this);
  35894. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35895. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35896. this.updateFloat = this._updateFloatForUniform;
  35897. this.updateFloat2 = this._updateFloat2ForUniform;
  35898. this.updateFloat3 = this._updateFloat3ForUniform;
  35899. this.updateFloat4 = this._updateFloat4ForUniform;
  35900. this.updateMatrix = this._updateMatrixForUniform;
  35901. this.updateVector3 = this._updateVector3ForUniform;
  35902. this.updateVector4 = this._updateVector4ForUniform;
  35903. this.updateColor3 = this._updateColor3ForUniform;
  35904. this.updateColor4 = this._updateColor4ForUniform;
  35905. }
  35906. }
  35907. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35908. // Properties
  35909. /**
  35910. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35911. * or just falling back on setUniformXXX calls.
  35912. */
  35913. get: function () {
  35914. return !this._noUBO;
  35915. },
  35916. enumerable: true,
  35917. configurable: true
  35918. });
  35919. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35920. /**
  35921. * Indicates if the WebGL underlying uniform buffer is in sync
  35922. * with the javascript cache data.
  35923. */
  35924. get: function () {
  35925. return !this._needSync;
  35926. },
  35927. enumerable: true,
  35928. configurable: true
  35929. });
  35930. /**
  35931. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35932. * Also, a dynamic UniformBuffer will disable cache verification and always
  35933. * update the underlying WebGL uniform buffer to the GPU.
  35934. */
  35935. UniformBuffer.prototype.isDynamic = function () {
  35936. return this._dynamic !== undefined;
  35937. };
  35938. /**
  35939. * The data cache on JS side.
  35940. */
  35941. UniformBuffer.prototype.getData = function () {
  35942. return this._bufferData;
  35943. };
  35944. /**
  35945. * The underlying WebGL Uniform buffer.
  35946. */
  35947. UniformBuffer.prototype.getBuffer = function () {
  35948. return this._buffer;
  35949. };
  35950. /**
  35951. * std140 layout specifies how to align data within an UBO structure.
  35952. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35953. * for specs.
  35954. */
  35955. UniformBuffer.prototype._fillAlignment = function (size) {
  35956. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35957. // and 4x4 matrices
  35958. // TODO : change if other types are used
  35959. var alignment;
  35960. if (size <= 2) {
  35961. alignment = size;
  35962. }
  35963. else {
  35964. alignment = 4;
  35965. }
  35966. if ((this._uniformLocationPointer % alignment) !== 0) {
  35967. var oldPointer = this._uniformLocationPointer;
  35968. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35969. var diff = this._uniformLocationPointer - oldPointer;
  35970. for (var i = 0; i < diff; i++) {
  35971. this._data.push(0);
  35972. }
  35973. }
  35974. };
  35975. /**
  35976. * Adds an uniform in the buffer.
  35977. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35978. * for the layout to be correct !
  35979. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35980. * @param {number|number[]} size Data size, or data directly.
  35981. */
  35982. UniformBuffer.prototype.addUniform = function (name, size) {
  35983. if (this._noUBO) {
  35984. return;
  35985. }
  35986. if (this._uniformLocations[name] !== undefined) {
  35987. // Already existing uniform
  35988. return;
  35989. }
  35990. // This function must be called in the order of the shader layout !
  35991. // size can be the size of the uniform, or data directly
  35992. var data;
  35993. if (size instanceof Array) {
  35994. data = size;
  35995. size = data.length;
  35996. }
  35997. else {
  35998. size = size;
  35999. data = [];
  36000. // Fill with zeros
  36001. for (var i = 0; i < size; i++) {
  36002. data.push(0);
  36003. }
  36004. }
  36005. this._fillAlignment(size);
  36006. this._uniformSizes[name] = size;
  36007. this._uniformLocations[name] = this._uniformLocationPointer;
  36008. this._uniformLocationPointer += size;
  36009. for (var i = 0; i < size; i++) {
  36010. this._data.push(data[i]);
  36011. }
  36012. this._needSync = true;
  36013. };
  36014. /**
  36015. * Wrapper for addUniform.
  36016. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36017. * @param {Matrix} mat A 4x4 matrix.
  36018. */
  36019. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36020. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36021. };
  36022. /**
  36023. * Wrapper for addUniform.
  36024. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36025. * @param {number} x
  36026. * @param {number} y
  36027. */
  36028. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36029. var temp = [x, y];
  36030. this.addUniform(name, temp);
  36031. };
  36032. /**
  36033. * Wrapper for addUniform.
  36034. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36035. * @param {number} x
  36036. * @param {number} y
  36037. * @param {number} z
  36038. */
  36039. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36040. var temp = [x, y, z];
  36041. this.addUniform(name, temp);
  36042. };
  36043. /**
  36044. * Wrapper for addUniform.
  36045. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36046. * @param {Color3} color
  36047. */
  36048. UniformBuffer.prototype.addColor3 = function (name, color) {
  36049. var temp = new Array();
  36050. color.toArray(temp);
  36051. this.addUniform(name, temp);
  36052. };
  36053. /**
  36054. * Wrapper for addUniform.
  36055. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36056. * @param {Color3} color
  36057. * @param {number} alpha
  36058. */
  36059. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36060. var temp = new Array();
  36061. color.toArray(temp);
  36062. temp.push(alpha);
  36063. this.addUniform(name, temp);
  36064. };
  36065. /**
  36066. * Wrapper for addUniform.
  36067. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36068. * @param {Vector3} vector
  36069. */
  36070. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36071. var temp = new Array();
  36072. vector.toArray(temp);
  36073. this.addUniform(name, temp);
  36074. };
  36075. /**
  36076. * Wrapper for addUniform.
  36077. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36078. */
  36079. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36080. this.addUniform(name, 12);
  36081. };
  36082. /**
  36083. * Wrapper for addUniform.
  36084. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36085. */
  36086. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36087. this.addUniform(name, 8);
  36088. };
  36089. /**
  36090. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36091. */
  36092. UniformBuffer.prototype.create = function () {
  36093. if (this._noUBO) {
  36094. return;
  36095. }
  36096. if (this._buffer) {
  36097. return; // nothing to do
  36098. }
  36099. // See spec, alignment must be filled as a vec4
  36100. this._fillAlignment(4);
  36101. this._bufferData = new Float32Array(this._data);
  36102. this._rebuild();
  36103. this._needSync = true;
  36104. };
  36105. UniformBuffer.prototype._rebuild = function () {
  36106. if (this._noUBO) {
  36107. return;
  36108. }
  36109. if (this._dynamic) {
  36110. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36111. }
  36112. else {
  36113. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36114. }
  36115. };
  36116. /**
  36117. * Updates the WebGL Uniform Buffer on the GPU.
  36118. * If the `dynamic` flag is set to true, no cache comparison is done.
  36119. * Otherwise, the buffer will be updated only if the cache differs.
  36120. */
  36121. UniformBuffer.prototype.update = function () {
  36122. if (!this._buffer) {
  36123. this.create();
  36124. return;
  36125. }
  36126. if (!this._dynamic && !this._needSync) {
  36127. return;
  36128. }
  36129. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36130. this._needSync = false;
  36131. };
  36132. /**
  36133. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36134. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36135. * @param {number[]|Float32Array} data Flattened data
  36136. * @param {number} size Size of the data.
  36137. */
  36138. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36139. var location = this._uniformLocations[uniformName];
  36140. if (location === undefined) {
  36141. if (this._buffer) {
  36142. // Cannot add an uniform if the buffer is already created
  36143. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36144. return;
  36145. }
  36146. this.addUniform(uniformName, size);
  36147. location = this._uniformLocations[uniformName];
  36148. }
  36149. if (!this._buffer) {
  36150. this.create();
  36151. }
  36152. if (!this._dynamic) {
  36153. // Cache for static uniform buffers
  36154. var changed = false;
  36155. for (var i = 0; i < size; i++) {
  36156. if (this._bufferData[location + i] !== data[i]) {
  36157. changed = true;
  36158. this._bufferData[location + i] = data[i];
  36159. }
  36160. }
  36161. this._needSync = this._needSync || changed;
  36162. }
  36163. else {
  36164. // No cache for dynamic
  36165. for (var i = 0; i < size; i++) {
  36166. this._bufferData[location + i] = data[i];
  36167. }
  36168. }
  36169. };
  36170. // Update methods
  36171. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36172. // To match std140, matrix must be realigned
  36173. for (var i = 0; i < 3; i++) {
  36174. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36175. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36176. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36177. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36178. }
  36179. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36180. };
  36181. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36182. this._currentEffect.setMatrix3x3(name, matrix);
  36183. };
  36184. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36185. this._currentEffect.setMatrix2x2(name, matrix);
  36186. };
  36187. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36188. // To match std140, matrix must be realigned
  36189. for (var i = 0; i < 2; i++) {
  36190. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36191. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36192. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36193. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36194. }
  36195. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36196. };
  36197. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36198. this._currentEffect.setFloat(name, x);
  36199. };
  36200. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36201. UniformBuffer._tempBuffer[0] = x;
  36202. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36203. };
  36204. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36205. if (suffix === void 0) { suffix = ""; }
  36206. this._currentEffect.setFloat2(name + suffix, x, y);
  36207. };
  36208. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36209. if (suffix === void 0) { suffix = ""; }
  36210. UniformBuffer._tempBuffer[0] = x;
  36211. UniformBuffer._tempBuffer[1] = y;
  36212. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36213. };
  36214. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36215. if (suffix === void 0) { suffix = ""; }
  36216. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36217. };
  36218. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36219. if (suffix === void 0) { suffix = ""; }
  36220. UniformBuffer._tempBuffer[0] = x;
  36221. UniformBuffer._tempBuffer[1] = y;
  36222. UniformBuffer._tempBuffer[2] = z;
  36223. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36224. };
  36225. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36226. if (suffix === void 0) { suffix = ""; }
  36227. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36228. };
  36229. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36230. if (suffix === void 0) { suffix = ""; }
  36231. UniformBuffer._tempBuffer[0] = x;
  36232. UniformBuffer._tempBuffer[1] = y;
  36233. UniformBuffer._tempBuffer[2] = z;
  36234. UniformBuffer._tempBuffer[3] = w;
  36235. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36236. };
  36237. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36238. this._currentEffect.setMatrix(name, mat);
  36239. };
  36240. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36241. this.updateUniform(name, mat.toArray(), 16);
  36242. };
  36243. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36244. this._currentEffect.setVector3(name, vector);
  36245. };
  36246. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36247. vector.toArray(UniformBuffer._tempBuffer);
  36248. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36249. };
  36250. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36251. this._currentEffect.setVector4(name, vector);
  36252. };
  36253. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36254. vector.toArray(UniformBuffer._tempBuffer);
  36255. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36256. };
  36257. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36258. if (suffix === void 0) { suffix = ""; }
  36259. this._currentEffect.setColor3(name + suffix, color);
  36260. };
  36261. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36262. if (suffix === void 0) { suffix = ""; }
  36263. color.toArray(UniformBuffer._tempBuffer);
  36264. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36265. };
  36266. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36267. if (suffix === void 0) { suffix = ""; }
  36268. this._currentEffect.setColor4(name + suffix, color, alpha);
  36269. };
  36270. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36271. if (suffix === void 0) { suffix = ""; }
  36272. color.toArray(UniformBuffer._tempBuffer);
  36273. UniformBuffer._tempBuffer[3] = alpha;
  36274. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36275. };
  36276. /**
  36277. * Sets a sampler uniform on the effect.
  36278. * @param {string} name Name of the sampler.
  36279. * @param {Texture} texture
  36280. */
  36281. UniformBuffer.prototype.setTexture = function (name, texture) {
  36282. this._currentEffect.setTexture(name, texture);
  36283. };
  36284. /**
  36285. * Directly updates the value of the uniform in the cache AND on the GPU.
  36286. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36287. * @param {number[]|Float32Array} data Flattened data
  36288. */
  36289. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36290. this.updateUniform(uniformName, data, data.length);
  36291. this.update();
  36292. };
  36293. /**
  36294. * Binds this uniform buffer to an effect.
  36295. * @param {Effect} effect
  36296. * @param {string} name Name of the uniform block in the shader.
  36297. */
  36298. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36299. this._currentEffect = effect;
  36300. if (this._noUBO || !this._buffer) {
  36301. return;
  36302. }
  36303. effect.bindUniformBuffer(this._buffer, name);
  36304. };
  36305. /**
  36306. * Disposes the uniform buffer.
  36307. */
  36308. UniformBuffer.prototype.dispose = function () {
  36309. if (this._noUBO) {
  36310. return;
  36311. }
  36312. var index = this._engine._uniformBuffers.indexOf(this);
  36313. if (index !== -1) {
  36314. this._engine._uniformBuffers.splice(index, 1);
  36315. }
  36316. if (!this._buffer) {
  36317. return;
  36318. }
  36319. if (this._engine._releaseBuffer(this._buffer)) {
  36320. this._buffer = null;
  36321. }
  36322. };
  36323. // Pool for avoiding memory leaks
  36324. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36325. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36326. return UniformBuffer;
  36327. }());
  36328. BABYLON.UniformBuffer = UniformBuffer;
  36329. })(BABYLON || (BABYLON = {}));
  36330. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36331. var BABYLON;
  36332. (function (BABYLON) {
  36333. /**
  36334. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36335. */
  36336. var VertexData = /** @class */ (function () {
  36337. function VertexData() {
  36338. }
  36339. /**
  36340. * Uses the passed data array to set the set the values for the specified kind of data
  36341. * @param data a linear array of floating numbers
  36342. * @param kind the type of data that is being set, eg positions, colors etc
  36343. */
  36344. VertexData.prototype.set = function (data, kind) {
  36345. switch (kind) {
  36346. case BABYLON.VertexBuffer.PositionKind:
  36347. this.positions = data;
  36348. break;
  36349. case BABYLON.VertexBuffer.NormalKind:
  36350. this.normals = data;
  36351. break;
  36352. case BABYLON.VertexBuffer.TangentKind:
  36353. this.tangents = data;
  36354. break;
  36355. case BABYLON.VertexBuffer.UVKind:
  36356. this.uvs = data;
  36357. break;
  36358. case BABYLON.VertexBuffer.UV2Kind:
  36359. this.uvs2 = data;
  36360. break;
  36361. case BABYLON.VertexBuffer.UV3Kind:
  36362. this.uvs3 = data;
  36363. break;
  36364. case BABYLON.VertexBuffer.UV4Kind:
  36365. this.uvs4 = data;
  36366. break;
  36367. case BABYLON.VertexBuffer.UV5Kind:
  36368. this.uvs5 = data;
  36369. break;
  36370. case BABYLON.VertexBuffer.UV6Kind:
  36371. this.uvs6 = data;
  36372. break;
  36373. case BABYLON.VertexBuffer.ColorKind:
  36374. this.colors = data;
  36375. break;
  36376. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36377. this.matricesIndices = data;
  36378. break;
  36379. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36380. this.matricesWeights = data;
  36381. break;
  36382. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36383. this.matricesIndicesExtra = data;
  36384. break;
  36385. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36386. this.matricesWeightsExtra = data;
  36387. break;
  36388. }
  36389. };
  36390. /**
  36391. * Associates the vertexData to the passed Mesh.
  36392. * Sets it as updatable or not (default `false`)
  36393. * @param mesh the mesh the vertexData is applied to
  36394. * @param updatable when used and having the value true allows new data to update the vertexData
  36395. * @returns the VertexData
  36396. */
  36397. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36398. this._applyTo(mesh, updatable);
  36399. return this;
  36400. };
  36401. /**
  36402. * Associates the vertexData to the passed Geometry.
  36403. * Sets it as updatable or not (default `false`)
  36404. * @param geometry the geometry the vertexData is applied to
  36405. * @param updatable when used and having the value true allows new data to update the vertexData
  36406. * @returns VertexData
  36407. */
  36408. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36409. this._applyTo(geometry, updatable);
  36410. return this;
  36411. };
  36412. /**
  36413. * Updates the associated mesh
  36414. * @param mesh the mesh to be updated
  36415. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36416. * @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
  36417. * @returns VertexData
  36418. */
  36419. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36420. this._update(mesh);
  36421. return this;
  36422. };
  36423. /**
  36424. * Updates the associated geometry
  36425. * @param geometry the geometry to be updated
  36426. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36427. * @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
  36428. * @returns VertexData.
  36429. */
  36430. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36431. this._update(geometry);
  36432. return this;
  36433. };
  36434. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36435. if (updatable === void 0) { updatable = false; }
  36436. if (this.positions) {
  36437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36438. }
  36439. if (this.normals) {
  36440. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36441. }
  36442. if (this.tangents) {
  36443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36444. }
  36445. if (this.uvs) {
  36446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36447. }
  36448. if (this.uvs2) {
  36449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36450. }
  36451. if (this.uvs3) {
  36452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36453. }
  36454. if (this.uvs4) {
  36455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36456. }
  36457. if (this.uvs5) {
  36458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36459. }
  36460. if (this.uvs6) {
  36461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36462. }
  36463. if (this.colors) {
  36464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36465. }
  36466. if (this.matricesIndices) {
  36467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36468. }
  36469. if (this.matricesWeights) {
  36470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36471. }
  36472. if (this.matricesIndicesExtra) {
  36473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36474. }
  36475. if (this.matricesWeightsExtra) {
  36476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36477. }
  36478. if (this.indices) {
  36479. meshOrGeometry.setIndices(this.indices, null, updatable);
  36480. }
  36481. return this;
  36482. };
  36483. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36484. if (this.positions) {
  36485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36486. }
  36487. if (this.normals) {
  36488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36489. }
  36490. if (this.tangents) {
  36491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36492. }
  36493. if (this.uvs) {
  36494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36495. }
  36496. if (this.uvs2) {
  36497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36498. }
  36499. if (this.uvs3) {
  36500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36501. }
  36502. if (this.uvs4) {
  36503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36504. }
  36505. if (this.uvs5) {
  36506. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36507. }
  36508. if (this.uvs6) {
  36509. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36510. }
  36511. if (this.colors) {
  36512. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36513. }
  36514. if (this.matricesIndices) {
  36515. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36516. }
  36517. if (this.matricesWeights) {
  36518. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36519. }
  36520. if (this.matricesIndicesExtra) {
  36521. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36522. }
  36523. if (this.matricesWeightsExtra) {
  36524. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36525. }
  36526. if (this.indices) {
  36527. meshOrGeometry.setIndices(this.indices, null);
  36528. }
  36529. return this;
  36530. };
  36531. /**
  36532. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36533. * @param matrix the transforming matrix
  36534. * @returns the VertexData
  36535. */
  36536. VertexData.prototype.transform = function (matrix) {
  36537. var transformed = BABYLON.Vector3.Zero();
  36538. var index;
  36539. if (this.positions) {
  36540. var position = BABYLON.Vector3.Zero();
  36541. for (index = 0; index < this.positions.length; index += 3) {
  36542. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36543. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36544. this.positions[index] = transformed.x;
  36545. this.positions[index + 1] = transformed.y;
  36546. this.positions[index + 2] = transformed.z;
  36547. }
  36548. }
  36549. if (this.normals) {
  36550. var normal = BABYLON.Vector3.Zero();
  36551. for (index = 0; index < this.normals.length; index += 3) {
  36552. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36553. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36554. this.normals[index] = transformed.x;
  36555. this.normals[index + 1] = transformed.y;
  36556. this.normals[index + 2] = transformed.z;
  36557. }
  36558. }
  36559. if (this.tangents) {
  36560. var tangent = BABYLON.Vector4.Zero();
  36561. var tangentTransformed = BABYLON.Vector4.Zero();
  36562. for (index = 0; index < this.tangents.length; index += 4) {
  36563. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36564. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36565. this.tangents[index] = tangentTransformed.x;
  36566. this.tangents[index + 1] = tangentTransformed.y;
  36567. this.tangents[index + 2] = tangentTransformed.z;
  36568. this.tangents[index + 3] = tangentTransformed.w;
  36569. }
  36570. }
  36571. return this;
  36572. };
  36573. /**
  36574. * Merges the passed VertexData into the current one
  36575. * @param other the VertexData to be merged into the current one
  36576. * @returns the modified VertexData
  36577. */
  36578. VertexData.prototype.merge = function (other) {
  36579. this._validate();
  36580. other._validate();
  36581. if (!this.normals !== !other.normals ||
  36582. !this.tangents !== !other.tangents ||
  36583. !this.uvs !== !other.uvs ||
  36584. !this.uvs2 !== !other.uvs2 ||
  36585. !this.uvs3 !== !other.uvs3 ||
  36586. !this.uvs4 !== !other.uvs4 ||
  36587. !this.uvs5 !== !other.uvs5 ||
  36588. !this.uvs6 !== !other.uvs6 ||
  36589. !this.colors !== !other.colors ||
  36590. !this.matricesIndices !== !other.matricesIndices ||
  36591. !this.matricesWeights !== !other.matricesWeights ||
  36592. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36593. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36594. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36595. }
  36596. if (other.indices) {
  36597. if (!this.indices) {
  36598. this.indices = [];
  36599. }
  36600. var offset = this.positions ? this.positions.length / 3 : 0;
  36601. for (var index = 0; index < other.indices.length; index++) {
  36602. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36603. this.indices.push(other.indices[index] + offset);
  36604. }
  36605. }
  36606. this.positions = this._mergeElement(this.positions, other.positions);
  36607. this.normals = this._mergeElement(this.normals, other.normals);
  36608. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36609. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36610. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36611. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36612. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36613. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36614. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36615. this.colors = this._mergeElement(this.colors, other.colors);
  36616. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36617. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36618. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36619. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36620. return this;
  36621. };
  36622. VertexData.prototype._mergeElement = function (source, other) {
  36623. if (!source) {
  36624. return other;
  36625. }
  36626. if (!other) {
  36627. return source;
  36628. }
  36629. var len = other.length + source.length;
  36630. var isSrcTypedArray = source instanceof Float32Array;
  36631. var isOthTypedArray = other instanceof Float32Array;
  36632. // use non-loop method when the source is Float32Array
  36633. if (isSrcTypedArray) {
  36634. var ret32 = new Float32Array(len);
  36635. ret32.set(source);
  36636. ret32.set(other, source.length);
  36637. return ret32;
  36638. // source is number[], when other is also use concat
  36639. }
  36640. else if (!isOthTypedArray) {
  36641. return source.concat(other);
  36642. // source is a number[], but other is a Float32Array, loop required
  36643. }
  36644. else {
  36645. var ret = source.slice(0); // copy source to a separate array
  36646. for (var i = 0, len = other.length; i < len; i++) {
  36647. ret.push(other[i]);
  36648. }
  36649. return ret;
  36650. }
  36651. };
  36652. VertexData.prototype._validate = function () {
  36653. if (!this.positions) {
  36654. throw new Error("Positions are required");
  36655. }
  36656. var getElementCount = function (kind, values) {
  36657. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36658. if ((values.length % stride) !== 0) {
  36659. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36660. }
  36661. return values.length / stride;
  36662. };
  36663. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36664. var validateElementCount = function (kind, values) {
  36665. var elementCount = getElementCount(kind, values);
  36666. if (elementCount !== positionsElementCount) {
  36667. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36668. }
  36669. };
  36670. if (this.normals)
  36671. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36672. if (this.tangents)
  36673. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36674. if (this.uvs)
  36675. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36676. if (this.uvs2)
  36677. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36678. if (this.uvs3)
  36679. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36680. if (this.uvs4)
  36681. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36682. if (this.uvs5)
  36683. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36684. if (this.uvs6)
  36685. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36686. if (this.colors)
  36687. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36688. if (this.matricesIndices)
  36689. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36690. if (this.matricesWeights)
  36691. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36692. if (this.matricesIndicesExtra)
  36693. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36694. if (this.matricesWeightsExtra)
  36695. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36696. };
  36697. /**
  36698. * Serializes the VertexData
  36699. * @returns a serialized object
  36700. */
  36701. VertexData.prototype.serialize = function () {
  36702. var serializationObject = this.serialize();
  36703. if (this.positions) {
  36704. serializationObject.positions = this.positions;
  36705. }
  36706. if (this.normals) {
  36707. serializationObject.normals = this.normals;
  36708. }
  36709. if (this.tangents) {
  36710. serializationObject.tangents = this.tangents;
  36711. }
  36712. if (this.uvs) {
  36713. serializationObject.uvs = this.uvs;
  36714. }
  36715. if (this.uvs2) {
  36716. serializationObject.uvs2 = this.uvs2;
  36717. }
  36718. if (this.uvs3) {
  36719. serializationObject.uvs3 = this.uvs3;
  36720. }
  36721. if (this.uvs4) {
  36722. serializationObject.uvs4 = this.uvs4;
  36723. }
  36724. if (this.uvs5) {
  36725. serializationObject.uvs5 = this.uvs5;
  36726. }
  36727. if (this.uvs6) {
  36728. serializationObject.uvs6 = this.uvs6;
  36729. }
  36730. if (this.colors) {
  36731. serializationObject.colors = this.colors;
  36732. }
  36733. if (this.matricesIndices) {
  36734. serializationObject.matricesIndices = this.matricesIndices;
  36735. serializationObject.matricesIndices._isExpanded = true;
  36736. }
  36737. if (this.matricesWeights) {
  36738. serializationObject.matricesWeights = this.matricesWeights;
  36739. }
  36740. if (this.matricesIndicesExtra) {
  36741. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36742. serializationObject.matricesIndicesExtra._isExpanded = true;
  36743. }
  36744. if (this.matricesWeightsExtra) {
  36745. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36746. }
  36747. serializationObject.indices = this.indices;
  36748. return serializationObject;
  36749. };
  36750. // Statics
  36751. /**
  36752. * Extracts the vertexData from a mesh
  36753. * @param mesh the mesh from which to extract the VertexData
  36754. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36755. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36756. * @returns the object VertexData associated to the passed mesh
  36757. */
  36758. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36759. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36760. };
  36761. /**
  36762. * Extracts the vertexData from the geometry
  36763. * @param geometry the geometry from which to extract the VertexData
  36764. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36765. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36766. * @returns the object VertexData associated to the passed mesh
  36767. */
  36768. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36769. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36770. };
  36771. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36772. var result = new VertexData();
  36773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36774. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36775. }
  36776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36777. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36778. }
  36779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36780. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36781. }
  36782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36783. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36784. }
  36785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36786. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36787. }
  36788. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36789. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36790. }
  36791. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36792. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36793. }
  36794. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36795. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36796. }
  36797. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36798. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36799. }
  36800. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36801. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36802. }
  36803. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36804. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36805. }
  36806. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36807. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36808. }
  36809. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36810. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36811. }
  36812. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36813. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36814. }
  36815. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36816. return result;
  36817. };
  36818. /**
  36819. * Creates the VertexData for a Ribbon
  36820. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36821. * * pathArray array of paths, each of which an array of successive Vector3
  36822. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36823. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36824. * * 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
  36825. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36826. * * 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)
  36827. * * 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)
  36828. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36829. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36830. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36831. * @returns the VertexData of the ribbon
  36832. */
  36833. VertexData.CreateRibbon = function (options) {
  36834. var pathArray = options.pathArray;
  36835. var closeArray = options.closeArray || false;
  36836. var closePath = options.closePath || false;
  36837. var invertUV = options.invertUV || false;
  36838. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36839. var offset = options.offset || defaultOffset;
  36840. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36841. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36842. var customUV = options.uvs;
  36843. var customColors = options.colors;
  36844. var positions = [];
  36845. var indices = [];
  36846. var normals = [];
  36847. var uvs = [];
  36848. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36849. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36850. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36851. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36852. var minlg; // minimal length among all paths from pathArray
  36853. var lg = []; // array of path lengths : nb of vertex per path
  36854. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36855. var p; // path iterator
  36856. var i; // point iterator
  36857. var j; // point iterator
  36858. // if single path in pathArray
  36859. if (pathArray.length < 2) {
  36860. var ar1 = [];
  36861. var ar2 = [];
  36862. for (i = 0; i < pathArray[0].length - offset; i++) {
  36863. ar1.push(pathArray[0][i]);
  36864. ar2.push(pathArray[0][i + offset]);
  36865. }
  36866. pathArray = [ar1, ar2];
  36867. }
  36868. // positions and horizontal distances (u)
  36869. var idc = 0;
  36870. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36871. var path;
  36872. var l;
  36873. minlg = pathArray[0].length;
  36874. var vectlg;
  36875. var dist;
  36876. for (p = 0; p < pathArray.length; p++) {
  36877. uTotalDistance[p] = 0;
  36878. us[p] = [0];
  36879. path = pathArray[p];
  36880. l = path.length;
  36881. minlg = (minlg < l) ? minlg : l;
  36882. j = 0;
  36883. while (j < l) {
  36884. positions.push(path[j].x, path[j].y, path[j].z);
  36885. if (j > 0) {
  36886. vectlg = path[j].subtract(path[j - 1]).length();
  36887. dist = vectlg + uTotalDistance[p];
  36888. us[p].push(dist);
  36889. uTotalDistance[p] = dist;
  36890. }
  36891. j++;
  36892. }
  36893. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36894. j--;
  36895. positions.push(path[0].x, path[0].y, path[0].z);
  36896. vectlg = path[j].subtract(path[0]).length();
  36897. dist = vectlg + uTotalDistance[p];
  36898. us[p].push(dist);
  36899. uTotalDistance[p] = dist;
  36900. }
  36901. lg[p] = l + closePathCorr;
  36902. idx[p] = idc;
  36903. idc += (l + closePathCorr);
  36904. }
  36905. // vertical distances (v)
  36906. var path1;
  36907. var path2;
  36908. var vertex1 = null;
  36909. var vertex2 = null;
  36910. for (i = 0; i < minlg + closePathCorr; i++) {
  36911. vTotalDistance[i] = 0;
  36912. vs[i] = [0];
  36913. for (p = 0; p < pathArray.length - 1; p++) {
  36914. path1 = pathArray[p];
  36915. path2 = pathArray[p + 1];
  36916. if (i === minlg) { // closePath
  36917. vertex1 = path1[0];
  36918. vertex2 = path2[0];
  36919. }
  36920. else {
  36921. vertex1 = path1[i];
  36922. vertex2 = path2[i];
  36923. }
  36924. vectlg = vertex2.subtract(vertex1).length();
  36925. dist = vectlg + vTotalDistance[i];
  36926. vs[i].push(dist);
  36927. vTotalDistance[i] = dist;
  36928. }
  36929. if (closeArray && vertex2 && vertex1) {
  36930. path1 = pathArray[p];
  36931. path2 = pathArray[0];
  36932. if (i === minlg) { // closePath
  36933. vertex2 = path2[0];
  36934. }
  36935. vectlg = vertex2.subtract(vertex1).length();
  36936. dist = vectlg + vTotalDistance[i];
  36937. vTotalDistance[i] = dist;
  36938. }
  36939. }
  36940. // uvs
  36941. var u;
  36942. var v;
  36943. if (customUV) {
  36944. for (p = 0; p < customUV.length; p++) {
  36945. uvs.push(customUV[p].x, customUV[p].y);
  36946. }
  36947. }
  36948. else {
  36949. for (p = 0; p < pathArray.length; p++) {
  36950. for (i = 0; i < minlg + closePathCorr; i++) {
  36951. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36952. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36953. if (invertUV) {
  36954. uvs.push(v, u);
  36955. }
  36956. else {
  36957. uvs.push(u, v);
  36958. }
  36959. }
  36960. }
  36961. }
  36962. // indices
  36963. p = 0; // path index
  36964. var pi = 0; // positions array index
  36965. var l1 = lg[p] - 1; // path1 length
  36966. var l2 = lg[p + 1] - 1; // path2 length
  36967. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36968. var shft = idx[1] - idx[0]; // shift
  36969. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36970. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36971. // 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
  36972. indices.push(pi, pi + shft, pi + 1);
  36973. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36974. pi += 1;
  36975. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36976. p++;
  36977. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36978. shft = idx[0] - idx[p];
  36979. l1 = lg[p] - 1;
  36980. l2 = lg[0] - 1;
  36981. }
  36982. else {
  36983. shft = idx[p + 1] - idx[p];
  36984. l1 = lg[p] - 1;
  36985. l2 = lg[p + 1] - 1;
  36986. }
  36987. pi = idx[p];
  36988. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36989. }
  36990. }
  36991. // normals
  36992. VertexData.ComputeNormals(positions, indices, normals);
  36993. if (closePath) { // update both the first and last vertex normals to their average value
  36994. var indexFirst = 0;
  36995. var indexLast = 0;
  36996. for (p = 0; p < pathArray.length; p++) {
  36997. indexFirst = idx[p] * 3;
  36998. if (p + 1 < pathArray.length) {
  36999. indexLast = (idx[p + 1] - 1) * 3;
  37000. }
  37001. else {
  37002. indexLast = normals.length - 3;
  37003. }
  37004. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37005. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37006. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37007. normals[indexLast] = normals[indexFirst];
  37008. normals[indexLast + 1] = normals[indexFirst + 1];
  37009. normals[indexLast + 2] = normals[indexFirst + 2];
  37010. }
  37011. }
  37012. // sides
  37013. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37014. // Colors
  37015. var colors = null;
  37016. if (customColors) {
  37017. colors = new Float32Array(customColors.length * 4);
  37018. for (var c = 0; c < customColors.length; c++) {
  37019. colors[c * 4] = customColors[c].r;
  37020. colors[c * 4 + 1] = customColors[c].g;
  37021. colors[c * 4 + 2] = customColors[c].b;
  37022. colors[c * 4 + 3] = customColors[c].a;
  37023. }
  37024. }
  37025. // Result
  37026. var vertexData = new VertexData();
  37027. var positions32 = new Float32Array(positions);
  37028. var normals32 = new Float32Array(normals);
  37029. var uvs32 = new Float32Array(uvs);
  37030. vertexData.indices = indices;
  37031. vertexData.positions = positions32;
  37032. vertexData.normals = normals32;
  37033. vertexData.uvs = uvs32;
  37034. if (colors) {
  37035. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37036. }
  37037. if (closePath) {
  37038. vertexData._idx = idx;
  37039. }
  37040. return vertexData;
  37041. };
  37042. /**
  37043. * Creates the VertexData for a box
  37044. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37045. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37046. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37047. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37048. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37049. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37050. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37051. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37052. * * 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)
  37053. * * 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)
  37054. * @returns the VertexData of the box
  37055. */
  37056. VertexData.CreateBox = function (options) {
  37057. var normalsSource = [
  37058. new BABYLON.Vector3(0, 0, 1),
  37059. new BABYLON.Vector3(0, 0, -1),
  37060. new BABYLON.Vector3(1, 0, 0),
  37061. new BABYLON.Vector3(-1, 0, 0),
  37062. new BABYLON.Vector3(0, 1, 0),
  37063. new BABYLON.Vector3(0, -1, 0)
  37064. ];
  37065. var indices = [];
  37066. var positions = [];
  37067. var normals = [];
  37068. var uvs = [];
  37069. var width = options.width || options.size || 1;
  37070. var height = options.height || options.size || 1;
  37071. var depth = options.depth || options.size || 1;
  37072. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37073. var faceUV = options.faceUV || new Array(6);
  37074. var faceColors = options.faceColors;
  37075. var colors = [];
  37076. // default face colors and UV if undefined
  37077. for (var f = 0; f < 6; f++) {
  37078. if (faceUV[f] === undefined) {
  37079. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37080. }
  37081. if (faceColors && faceColors[f] === undefined) {
  37082. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37083. }
  37084. }
  37085. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37086. // Create each face in turn.
  37087. for (var index = 0; index < normalsSource.length; index++) {
  37088. var normal = normalsSource[index];
  37089. // Get two vectors perpendicular to the face normal and to each other.
  37090. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37091. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37092. // Six indices (two triangles) per face.
  37093. var verticesLength = positions.length / 3;
  37094. indices.push(verticesLength);
  37095. indices.push(verticesLength + 1);
  37096. indices.push(verticesLength + 2);
  37097. indices.push(verticesLength);
  37098. indices.push(verticesLength + 2);
  37099. indices.push(verticesLength + 3);
  37100. // Four vertices per face.
  37101. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37102. positions.push(vertex.x, vertex.y, vertex.z);
  37103. normals.push(normal.x, normal.y, normal.z);
  37104. uvs.push(faceUV[index].z, faceUV[index].w);
  37105. if (faceColors) {
  37106. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37107. }
  37108. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37109. positions.push(vertex.x, vertex.y, vertex.z);
  37110. normals.push(normal.x, normal.y, normal.z);
  37111. uvs.push(faceUV[index].x, faceUV[index].w);
  37112. if (faceColors) {
  37113. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37114. }
  37115. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37116. positions.push(vertex.x, vertex.y, vertex.z);
  37117. normals.push(normal.x, normal.y, normal.z);
  37118. uvs.push(faceUV[index].x, faceUV[index].y);
  37119. if (faceColors) {
  37120. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37121. }
  37122. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37123. positions.push(vertex.x, vertex.y, vertex.z);
  37124. normals.push(normal.x, normal.y, normal.z);
  37125. uvs.push(faceUV[index].z, faceUV[index].y);
  37126. if (faceColors) {
  37127. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37128. }
  37129. }
  37130. // sides
  37131. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37132. // Result
  37133. var vertexData = new VertexData();
  37134. vertexData.indices = indices;
  37135. vertexData.positions = positions;
  37136. vertexData.normals = normals;
  37137. vertexData.uvs = uvs;
  37138. if (faceColors) {
  37139. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37140. vertexData.colors = totalColors;
  37141. }
  37142. return vertexData;
  37143. };
  37144. /**
  37145. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37146. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37147. * * segments sets the number of horizontal strips optional, default 32
  37148. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37149. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37150. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37151. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37152. * * 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
  37153. * * 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
  37154. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37155. * * 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)
  37156. * * 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)
  37157. * @returns the VertexData of the ellipsoid
  37158. */
  37159. VertexData.CreateSphere = function (options) {
  37160. var segments = options.segments || 32;
  37161. var diameterX = options.diameterX || options.diameter || 1;
  37162. var diameterY = options.diameterY || options.diameter || 1;
  37163. var diameterZ = options.diameterZ || options.diameter || 1;
  37164. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37165. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37166. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37167. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37168. var totalZRotationSteps = 2 + segments;
  37169. var totalYRotationSteps = 2 * totalZRotationSteps;
  37170. var indices = [];
  37171. var positions = [];
  37172. var normals = [];
  37173. var uvs = [];
  37174. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37175. var normalizedZ = zRotationStep / totalZRotationSteps;
  37176. var angleZ = normalizedZ * Math.PI * slice;
  37177. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37178. var normalizedY = yRotationStep / totalYRotationSteps;
  37179. var angleY = normalizedY * Math.PI * 2 * arc;
  37180. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37181. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37182. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37183. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37184. var vertex = complete.multiply(radius);
  37185. var normal = complete.divide(radius).normalize();
  37186. positions.push(vertex.x, vertex.y, vertex.z);
  37187. normals.push(normal.x, normal.y, normal.z);
  37188. uvs.push(normalizedY, normalizedZ);
  37189. }
  37190. if (zRotationStep > 0) {
  37191. var verticesCount = positions.length / 3;
  37192. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37193. indices.push((firstIndex));
  37194. indices.push((firstIndex + 1));
  37195. indices.push(firstIndex + totalYRotationSteps + 1);
  37196. indices.push((firstIndex + totalYRotationSteps + 1));
  37197. indices.push((firstIndex + 1));
  37198. indices.push((firstIndex + totalYRotationSteps + 2));
  37199. }
  37200. }
  37201. }
  37202. // Sides
  37203. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37204. // Result
  37205. var vertexData = new VertexData();
  37206. vertexData.indices = indices;
  37207. vertexData.positions = positions;
  37208. vertexData.normals = normals;
  37209. vertexData.uvs = uvs;
  37210. return vertexData;
  37211. };
  37212. /**
  37213. * Creates the VertexData for a cylinder, cone or prism
  37214. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37215. * * height sets the height (y direction) of the cylinder, optional, default 2
  37216. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37217. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37218. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37219. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37220. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37221. * * 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
  37222. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37223. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37224. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37225. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37226. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37227. * * 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)
  37228. * * 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)
  37229. * @returns the VertexData of the cylinder, cone or prism
  37230. */
  37231. VertexData.CreateCylinder = function (options) {
  37232. var height = options.height || 2;
  37233. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37234. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37235. var tessellation = options.tessellation || 24;
  37236. var subdivisions = options.subdivisions || 1;
  37237. var hasRings = options.hasRings ? true : false;
  37238. var enclose = options.enclose ? true : false;
  37239. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37240. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37241. var faceUV = options.faceUV || new Array(3);
  37242. var faceColors = options.faceColors;
  37243. // default face colors and UV if undefined
  37244. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37245. var ringNb = (hasRings) ? subdivisions : 1;
  37246. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37247. var f;
  37248. for (f = 0; f < surfaceNb; f++) {
  37249. if (faceColors && faceColors[f] === undefined) {
  37250. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37251. }
  37252. }
  37253. for (f = 0; f < surfaceNb; f++) {
  37254. if (faceUV && faceUV[f] === undefined) {
  37255. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37256. }
  37257. }
  37258. var indices = new Array();
  37259. var positions = new Array();
  37260. var normals = new Array();
  37261. var uvs = new Array();
  37262. var colors = new Array();
  37263. var angle_step = Math.PI * 2 * arc / tessellation;
  37264. var angle;
  37265. var h;
  37266. var radius;
  37267. var tan = (diameterBottom - diameterTop) / 2 / height;
  37268. var ringVertex = BABYLON.Vector3.Zero();
  37269. var ringNormal = BABYLON.Vector3.Zero();
  37270. var ringFirstVertex = BABYLON.Vector3.Zero();
  37271. var ringFirstNormal = BABYLON.Vector3.Zero();
  37272. var quadNormal = BABYLON.Vector3.Zero();
  37273. var Y = BABYLON.Axis.Y;
  37274. // positions, normals, uvs
  37275. var i;
  37276. var j;
  37277. var r;
  37278. var ringIdx = 1;
  37279. var s = 1; // surface index
  37280. var cs = 0;
  37281. var v = 0;
  37282. for (i = 0; i <= subdivisions; i++) {
  37283. h = i / subdivisions;
  37284. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37285. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37286. for (r = 0; r < ringIdx; r++) {
  37287. if (hasRings) {
  37288. s += r;
  37289. }
  37290. if (enclose) {
  37291. s += 2 * r;
  37292. }
  37293. for (j = 0; j <= tessellation; j++) {
  37294. angle = j * angle_step;
  37295. // position
  37296. ringVertex.x = Math.cos(-angle) * radius;
  37297. ringVertex.y = -height / 2 + h * height;
  37298. ringVertex.z = Math.sin(-angle) * radius;
  37299. // normal
  37300. if (diameterTop === 0 && i === subdivisions) {
  37301. // if no top cap, reuse former normals
  37302. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37303. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37304. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37305. }
  37306. else {
  37307. ringNormal.x = ringVertex.x;
  37308. ringNormal.z = ringVertex.z;
  37309. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37310. ringNormal.normalize();
  37311. }
  37312. // keep first ring vertex values for enclose
  37313. if (j === 0) {
  37314. ringFirstVertex.copyFrom(ringVertex);
  37315. ringFirstNormal.copyFrom(ringNormal);
  37316. }
  37317. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37318. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37319. if (hasRings) {
  37320. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37321. }
  37322. else {
  37323. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37324. }
  37325. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37326. if (faceColors) {
  37327. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37328. }
  37329. }
  37330. // if enclose, add four vertices and their dedicated normals
  37331. if (arc !== 1 && enclose) {
  37332. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37333. positions.push(0, ringVertex.y, 0);
  37334. positions.push(0, ringVertex.y, 0);
  37335. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37336. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37337. quadNormal.normalize();
  37338. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37339. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37340. quadNormal.normalize();
  37341. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37342. if (hasRings) {
  37343. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37344. }
  37345. else {
  37346. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37347. }
  37348. uvs.push(faceUV[s + 1].x, v);
  37349. uvs.push(faceUV[s + 1].z, v);
  37350. if (hasRings) {
  37351. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37352. }
  37353. else {
  37354. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37355. }
  37356. uvs.push(faceUV[s + 2].x, v);
  37357. uvs.push(faceUV[s + 2].z, v);
  37358. if (faceColors) {
  37359. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37360. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37361. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37362. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37363. }
  37364. }
  37365. if (cs !== s) {
  37366. cs = s;
  37367. }
  37368. }
  37369. }
  37370. // indices
  37371. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37372. var s;
  37373. i = 0;
  37374. for (s = 0; s < subdivisions; s++) {
  37375. var i0 = 0;
  37376. var i1 = 0;
  37377. var i2 = 0;
  37378. var i3 = 0;
  37379. for (j = 0; j < tessellation; j++) {
  37380. i0 = i * (e + 1) + j;
  37381. i1 = (i + 1) * (e + 1) + j;
  37382. i2 = i * (e + 1) + (j + 1);
  37383. i3 = (i + 1) * (e + 1) + (j + 1);
  37384. indices.push(i0, i1, i2);
  37385. indices.push(i3, i2, i1);
  37386. }
  37387. if (arc !== 1 && enclose) { // if enclose, add two quads
  37388. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37389. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37390. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37391. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37392. }
  37393. i = (hasRings) ? (i + 2) : (i + 1);
  37394. }
  37395. // Caps
  37396. var createCylinderCap = function (isTop) {
  37397. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37398. if (radius === 0) {
  37399. return;
  37400. }
  37401. // Cap positions, normals & uvs
  37402. var angle;
  37403. var circleVector;
  37404. var i;
  37405. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37406. var c = null;
  37407. if (faceColors) {
  37408. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37409. }
  37410. // cap center
  37411. var vbase = positions.length / 3;
  37412. var offset = isTop ? height / 2 : -height / 2;
  37413. var center = new BABYLON.Vector3(0, offset, 0);
  37414. positions.push(center.x, center.y, center.z);
  37415. normals.push(0, isTop ? 1 : -1, 0);
  37416. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37417. if (c) {
  37418. colors.push(c.r, c.g, c.b, c.a);
  37419. }
  37420. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37421. for (i = 0; i <= tessellation; i++) {
  37422. angle = Math.PI * 2 * i * arc / tessellation;
  37423. var cos = Math.cos(-angle);
  37424. var sin = Math.sin(-angle);
  37425. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37426. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37427. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37428. normals.push(0, isTop ? 1 : -1, 0);
  37429. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37430. if (c) {
  37431. colors.push(c.r, c.g, c.b, c.a);
  37432. }
  37433. }
  37434. // Cap indices
  37435. for (i = 0; i < tessellation; i++) {
  37436. if (!isTop) {
  37437. indices.push(vbase);
  37438. indices.push(vbase + (i + 1));
  37439. indices.push(vbase + (i + 2));
  37440. }
  37441. else {
  37442. indices.push(vbase);
  37443. indices.push(vbase + (i + 2));
  37444. indices.push(vbase + (i + 1));
  37445. }
  37446. }
  37447. };
  37448. // add caps to geometry
  37449. createCylinderCap(false);
  37450. createCylinderCap(true);
  37451. // Sides
  37452. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37453. var vertexData = new VertexData();
  37454. vertexData.indices = indices;
  37455. vertexData.positions = positions;
  37456. vertexData.normals = normals;
  37457. vertexData.uvs = uvs;
  37458. if (faceColors) {
  37459. vertexData.colors = colors;
  37460. }
  37461. return vertexData;
  37462. };
  37463. /**
  37464. * Creates the VertexData for a torus
  37465. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37466. * * diameter the diameter of the torus, optional default 1
  37467. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37468. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37469. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37470. * * 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)
  37471. * * 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)
  37472. * @returns the VertexData of the torus
  37473. */
  37474. VertexData.CreateTorus = function (options) {
  37475. var indices = [];
  37476. var positions = [];
  37477. var normals = [];
  37478. var uvs = [];
  37479. var diameter = options.diameter || 1;
  37480. var thickness = options.thickness || 0.5;
  37481. var tessellation = options.tessellation || 16;
  37482. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37483. var stride = tessellation + 1;
  37484. for (var i = 0; i <= tessellation; i++) {
  37485. var u = i / tessellation;
  37486. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37487. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37488. for (var j = 0; j <= tessellation; j++) {
  37489. var v = 1 - j / tessellation;
  37490. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37491. var dx = Math.cos(innerAngle);
  37492. var dy = Math.sin(innerAngle);
  37493. // Create a vertex.
  37494. var normal = new BABYLON.Vector3(dx, dy, 0);
  37495. var position = normal.scale(thickness / 2);
  37496. var textureCoordinate = new BABYLON.Vector2(u, v);
  37497. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37498. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37499. positions.push(position.x, position.y, position.z);
  37500. normals.push(normal.x, normal.y, normal.z);
  37501. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37502. // And create indices for two triangles.
  37503. var nextI = (i + 1) % stride;
  37504. var nextJ = (j + 1) % stride;
  37505. indices.push(i * stride + j);
  37506. indices.push(i * stride + nextJ);
  37507. indices.push(nextI * stride + j);
  37508. indices.push(i * stride + nextJ);
  37509. indices.push(nextI * stride + nextJ);
  37510. indices.push(nextI * stride + j);
  37511. }
  37512. }
  37513. // Sides
  37514. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37515. // Result
  37516. var vertexData = new VertexData();
  37517. vertexData.indices = indices;
  37518. vertexData.positions = positions;
  37519. vertexData.normals = normals;
  37520. vertexData.uvs = uvs;
  37521. return vertexData;
  37522. };
  37523. /**
  37524. * Creates the VertexData of the LineSystem
  37525. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37526. * - lines an array of lines, each line being an array of successive Vector3
  37527. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37528. * @returns the VertexData of the LineSystem
  37529. */
  37530. VertexData.CreateLineSystem = function (options) {
  37531. var indices = [];
  37532. var positions = [];
  37533. var lines = options.lines;
  37534. var colors = options.colors;
  37535. var vertexColors = [];
  37536. var idx = 0;
  37537. for (var l = 0; l < lines.length; l++) {
  37538. var points = lines[l];
  37539. for (var index = 0; index < points.length; index++) {
  37540. positions.push(points[index].x, points[index].y, points[index].z);
  37541. if (colors) {
  37542. var color = colors[l];
  37543. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37544. }
  37545. if (index > 0) {
  37546. indices.push(idx - 1);
  37547. indices.push(idx);
  37548. }
  37549. idx++;
  37550. }
  37551. }
  37552. var vertexData = new VertexData();
  37553. vertexData.indices = indices;
  37554. vertexData.positions = positions;
  37555. if (colors) {
  37556. vertexData.colors = vertexColors;
  37557. }
  37558. return vertexData;
  37559. };
  37560. /**
  37561. * Create the VertexData for a DashedLines
  37562. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37563. * - points an array successive Vector3
  37564. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37565. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37566. * - dashNb the intended total number of dashes, optional, default 200
  37567. * @returns the VertexData for the DashedLines
  37568. */
  37569. VertexData.CreateDashedLines = function (options) {
  37570. var dashSize = options.dashSize || 3;
  37571. var gapSize = options.gapSize || 1;
  37572. var dashNb = options.dashNb || 200;
  37573. var points = options.points;
  37574. var positions = new Array();
  37575. var indices = new Array();
  37576. var curvect = BABYLON.Vector3.Zero();
  37577. var lg = 0;
  37578. var nb = 0;
  37579. var shft = 0;
  37580. var dashshft = 0;
  37581. var curshft = 0;
  37582. var idx = 0;
  37583. var i = 0;
  37584. for (i = 0; i < points.length - 1; i++) {
  37585. points[i + 1].subtractToRef(points[i], curvect);
  37586. lg += curvect.length();
  37587. }
  37588. shft = lg / dashNb;
  37589. dashshft = dashSize * shft / (dashSize + gapSize);
  37590. for (i = 0; i < points.length - 1; i++) {
  37591. points[i + 1].subtractToRef(points[i], curvect);
  37592. nb = Math.floor(curvect.length() / shft);
  37593. curvect.normalize();
  37594. for (var j = 0; j < nb; j++) {
  37595. curshft = shft * j;
  37596. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37597. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37598. indices.push(idx, idx + 1);
  37599. idx += 2;
  37600. }
  37601. }
  37602. // Result
  37603. var vertexData = new VertexData();
  37604. vertexData.positions = positions;
  37605. vertexData.indices = indices;
  37606. return vertexData;
  37607. };
  37608. /**
  37609. * Creates the VertexData for a Ground
  37610. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37611. * - width the width (x direction) of the ground, optional, default 1
  37612. * - height the height (z direction) of the ground, optional, default 1
  37613. * - subdivisions the number of subdivisions per side, optional, default 1
  37614. * @returns the VertexData of the Ground
  37615. */
  37616. VertexData.CreateGround = function (options) {
  37617. var indices = [];
  37618. var positions = [];
  37619. var normals = [];
  37620. var uvs = [];
  37621. var row, col;
  37622. var width = options.width || 1;
  37623. var height = options.height || 1;
  37624. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37625. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37626. for (row = 0; row <= subdivisionsY; row++) {
  37627. for (col = 0; col <= subdivisionsX; col++) {
  37628. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37629. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37630. positions.push(position.x, position.y, position.z);
  37631. normals.push(normal.x, normal.y, normal.z);
  37632. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37633. }
  37634. }
  37635. for (row = 0; row < subdivisionsY; row++) {
  37636. for (col = 0; col < subdivisionsX; col++) {
  37637. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37638. indices.push(col + 1 + row * (subdivisionsX + 1));
  37639. indices.push(col + row * (subdivisionsX + 1));
  37640. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37641. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37642. indices.push(col + row * (subdivisionsX + 1));
  37643. }
  37644. }
  37645. // Result
  37646. var vertexData = new VertexData();
  37647. vertexData.indices = indices;
  37648. vertexData.positions = positions;
  37649. vertexData.normals = normals;
  37650. vertexData.uvs = uvs;
  37651. return vertexData;
  37652. };
  37653. /**
  37654. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37655. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37656. * * xmin the ground minimum X coordinate, optional, default -1
  37657. * * zmin the ground minimum Z coordinate, optional, default -1
  37658. * * xmax the ground maximum X coordinate, optional, default 1
  37659. * * zmax the ground maximum Z coordinate, optional, default 1
  37660. * * 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}
  37661. * * 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}
  37662. * @returns the VertexData of the TiledGround
  37663. */
  37664. VertexData.CreateTiledGround = function (options) {
  37665. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37666. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37667. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37668. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37669. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37670. var precision = options.precision || { w: 1, h: 1 };
  37671. var indices = new Array();
  37672. var positions = new Array();
  37673. var normals = new Array();
  37674. var uvs = new Array();
  37675. var row, col, tileRow, tileCol;
  37676. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37677. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37678. precision.w = (precision.w < 1) ? 1 : precision.w;
  37679. precision.h = (precision.h < 1) ? 1 : precision.h;
  37680. var tileSize = {
  37681. 'w': (xmax - xmin) / subdivisions.w,
  37682. 'h': (zmax - zmin) / subdivisions.h
  37683. };
  37684. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37685. // Indices
  37686. var base = positions.length / 3;
  37687. var rowLength = precision.w + 1;
  37688. for (row = 0; row < precision.h; row++) {
  37689. for (col = 0; col < precision.w; col++) {
  37690. var square = [
  37691. base + col + row * rowLength,
  37692. base + (col + 1) + row * rowLength,
  37693. base + (col + 1) + (row + 1) * rowLength,
  37694. base + col + (row + 1) * rowLength
  37695. ];
  37696. indices.push(square[1]);
  37697. indices.push(square[2]);
  37698. indices.push(square[3]);
  37699. indices.push(square[0]);
  37700. indices.push(square[1]);
  37701. indices.push(square[3]);
  37702. }
  37703. }
  37704. // Position, normals and uvs
  37705. var position = BABYLON.Vector3.Zero();
  37706. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37707. for (row = 0; row <= precision.h; row++) {
  37708. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37709. for (col = 0; col <= precision.w; col++) {
  37710. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37711. position.y = 0;
  37712. positions.push(position.x, position.y, position.z);
  37713. normals.push(normal.x, normal.y, normal.z);
  37714. uvs.push(col / precision.w, row / precision.h);
  37715. }
  37716. }
  37717. }
  37718. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37719. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37720. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37721. }
  37722. }
  37723. // Result
  37724. var vertexData = new VertexData();
  37725. vertexData.indices = indices;
  37726. vertexData.positions = positions;
  37727. vertexData.normals = normals;
  37728. vertexData.uvs = uvs;
  37729. return vertexData;
  37730. };
  37731. /**
  37732. * Creates the VertexData of the Ground designed from a heightmap
  37733. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37734. * * width the width (x direction) of the ground
  37735. * * height the height (z direction) of the ground
  37736. * * subdivisions the number of subdivisions per side
  37737. * * minHeight the minimum altitude on the ground, optional, default 0
  37738. * * maxHeight the maximum altitude on the ground, optional default 1
  37739. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37740. * * buffer the array holding the image color data
  37741. * * bufferWidth the width of image
  37742. * * bufferHeight the height of image
  37743. * @returns the VertexData of the Ground designed from a heightmap
  37744. */
  37745. VertexData.CreateGroundFromHeightMap = function (options) {
  37746. var indices = [];
  37747. var positions = [];
  37748. var normals = [];
  37749. var uvs = [];
  37750. var row, col;
  37751. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37752. // Vertices
  37753. for (row = 0; row <= options.subdivisions; row++) {
  37754. for (col = 0; col <= options.subdivisions; col++) {
  37755. 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));
  37756. // Compute height
  37757. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37758. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37759. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37760. var r = options.buffer[pos] / 255.0;
  37761. var g = options.buffer[pos + 1] / 255.0;
  37762. var b = options.buffer[pos + 2] / 255.0;
  37763. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37764. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37765. // Add vertex
  37766. positions.push(position.x, position.y, position.z);
  37767. normals.push(0, 0, 0);
  37768. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37769. }
  37770. }
  37771. // Indices
  37772. for (row = 0; row < options.subdivisions; row++) {
  37773. for (col = 0; col < options.subdivisions; col++) {
  37774. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37775. indices.push(col + 1 + row * (options.subdivisions + 1));
  37776. indices.push(col + row * (options.subdivisions + 1));
  37777. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37778. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37779. indices.push(col + row * (options.subdivisions + 1));
  37780. }
  37781. }
  37782. // Normals
  37783. VertexData.ComputeNormals(positions, indices, normals);
  37784. // Result
  37785. var vertexData = new VertexData();
  37786. vertexData.indices = indices;
  37787. vertexData.positions = positions;
  37788. vertexData.normals = normals;
  37789. vertexData.uvs = uvs;
  37790. return vertexData;
  37791. };
  37792. /**
  37793. * Creates the VertexData for a Plane
  37794. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37795. * * size sets the width and height of the plane to the value of size, optional default 1
  37796. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37797. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37798. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37799. * * 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)
  37800. * * 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)
  37801. * @returns the VertexData of the box
  37802. */
  37803. VertexData.CreatePlane = function (options) {
  37804. var indices = [];
  37805. var positions = [];
  37806. var normals = [];
  37807. var uvs = [];
  37808. var width = options.width || options.size || 1;
  37809. var height = options.height || options.size || 1;
  37810. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37811. // Vertices
  37812. var halfWidth = width / 2.0;
  37813. var halfHeight = height / 2.0;
  37814. positions.push(-halfWidth, -halfHeight, 0);
  37815. normals.push(0, 0, -1.0);
  37816. uvs.push(0.0, 0.0);
  37817. positions.push(halfWidth, -halfHeight, 0);
  37818. normals.push(0, 0, -1.0);
  37819. uvs.push(1.0, 0.0);
  37820. positions.push(halfWidth, halfHeight, 0);
  37821. normals.push(0, 0, -1.0);
  37822. uvs.push(1.0, 1.0);
  37823. positions.push(-halfWidth, halfHeight, 0);
  37824. normals.push(0, 0, -1.0);
  37825. uvs.push(0.0, 1.0);
  37826. // Indices
  37827. indices.push(0);
  37828. indices.push(1);
  37829. indices.push(2);
  37830. indices.push(0);
  37831. indices.push(2);
  37832. indices.push(3);
  37833. // Sides
  37834. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37835. // Result
  37836. var vertexData = new VertexData();
  37837. vertexData.indices = indices;
  37838. vertexData.positions = positions;
  37839. vertexData.normals = normals;
  37840. vertexData.uvs = uvs;
  37841. return vertexData;
  37842. };
  37843. /**
  37844. * Creates the VertexData of the Disc or regular Polygon
  37845. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37846. * * radius the radius of the disc, optional default 0.5
  37847. * * tessellation the number of polygon sides, optional, default 64
  37848. * * 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
  37849. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37850. * * 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)
  37851. * * 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)
  37852. * @returns the VertexData of the box
  37853. */
  37854. VertexData.CreateDisc = function (options) {
  37855. var positions = new Array();
  37856. var indices = new Array();
  37857. var normals = new Array();
  37858. var uvs = new Array();
  37859. var radius = options.radius || 0.5;
  37860. var tessellation = options.tessellation || 64;
  37861. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37862. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37863. // positions and uvs
  37864. positions.push(0, 0, 0); // disc center first
  37865. uvs.push(0.5, 0.5);
  37866. var theta = Math.PI * 2 * arc;
  37867. var step = theta / tessellation;
  37868. for (var a = 0; a < theta; a += step) {
  37869. var x = Math.cos(a);
  37870. var y = Math.sin(a);
  37871. var u = (x + 1) / 2;
  37872. var v = (1 - y) / 2;
  37873. positions.push(radius * x, radius * y, 0);
  37874. uvs.push(u, v);
  37875. }
  37876. if (arc === 1) {
  37877. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37878. uvs.push(uvs[2], uvs[3]);
  37879. }
  37880. //indices
  37881. var vertexNb = positions.length / 3;
  37882. for (var i = 1; i < vertexNb - 1; i++) {
  37883. indices.push(i + 1, 0, i);
  37884. }
  37885. // result
  37886. VertexData.ComputeNormals(positions, indices, normals);
  37887. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37888. var vertexData = new VertexData();
  37889. vertexData.indices = indices;
  37890. vertexData.positions = positions;
  37891. vertexData.normals = normals;
  37892. vertexData.uvs = uvs;
  37893. return vertexData;
  37894. };
  37895. /**
  37896. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37897. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37898. * @param polygon a mesh built from polygonTriangulation.build()
  37899. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37900. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37901. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37902. * @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)
  37903. * @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)
  37904. * @returns the VertexData of the Polygon
  37905. */
  37906. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37907. var faceUV = fUV || new Array(3);
  37908. var faceColors = fColors;
  37909. var colors = [];
  37910. // default face colors and UV if undefined
  37911. for (var f = 0; f < 3; f++) {
  37912. if (faceUV[f] === undefined) {
  37913. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37914. }
  37915. if (faceColors && faceColors[f] === undefined) {
  37916. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37917. }
  37918. }
  37919. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37920. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37921. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37922. var indices = polygon.getIndices();
  37923. // set face colours and textures
  37924. var idx = 0;
  37925. var face = 0;
  37926. for (var index = 0; index < normals.length; index += 3) {
  37927. //Edge Face no. 1
  37928. if (Math.abs(normals[index + 1]) < 0.001) {
  37929. face = 1;
  37930. }
  37931. //Top Face no. 0
  37932. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37933. face = 0;
  37934. }
  37935. //Bottom Face no. 2
  37936. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37937. face = 2;
  37938. }
  37939. idx = index / 3;
  37940. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37941. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37942. if (faceColors) {
  37943. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37944. }
  37945. }
  37946. // sides
  37947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37948. // Result
  37949. var vertexData = new VertexData();
  37950. vertexData.indices = indices;
  37951. vertexData.positions = positions;
  37952. vertexData.normals = normals;
  37953. vertexData.uvs = uvs;
  37954. if (faceColors) {
  37955. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37956. vertexData.colors = totalColors;
  37957. }
  37958. return vertexData;
  37959. };
  37960. /**
  37961. * Creates the VertexData of the IcoSphere
  37962. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37963. * * radius the radius of the IcoSphere, optional default 1
  37964. * * radiusX allows stretching in the x direction, optional, default radius
  37965. * * radiusY allows stretching in the y direction, optional, default radius
  37966. * * radiusZ allows stretching in the z direction, optional, default radius
  37967. * * flat when true creates a flat shaded mesh, optional, default true
  37968. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37969. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37970. * * 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)
  37971. * * 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)
  37972. * @returns the VertexData of the IcoSphere
  37973. */
  37974. VertexData.CreateIcoSphere = function (options) {
  37975. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37976. var radius = options.radius || 1;
  37977. var flat = (options.flat === undefined) ? true : options.flat;
  37978. var subdivisions = options.subdivisions || 4;
  37979. var radiusX = options.radiusX || radius;
  37980. var radiusY = options.radiusY || radius;
  37981. var radiusZ = options.radiusZ || radius;
  37982. var t = (1 + Math.sqrt(5)) / 2;
  37983. // 12 vertex x,y,z
  37984. var ico_vertices = [
  37985. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37986. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37987. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37988. ];
  37989. // index of 3 vertex makes a face of icopshere
  37990. var ico_indices = [
  37991. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37992. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37993. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37994. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37995. ];
  37996. // vertex for uv have aliased position, not for UV
  37997. var vertices_unalias_id = [
  37998. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37999. // vertex alias
  38000. 0,
  38001. 2,
  38002. 3,
  38003. 3,
  38004. 3,
  38005. 4,
  38006. 7,
  38007. 8,
  38008. 9,
  38009. 9,
  38010. 10,
  38011. 11 // 23: B + 12
  38012. ];
  38013. // uv as integer step (not pixels !)
  38014. var ico_vertexuv = [
  38015. 5, 1, 3, 1, 6, 4, 0, 0,
  38016. 5, 3, 4, 2, 2, 2, 4, 0,
  38017. 2, 0, 1, 1, 6, 0, 6, 2,
  38018. // vertex alias (for same vertex on different faces)
  38019. 0, 4,
  38020. 3, 3,
  38021. 4, 4,
  38022. 3, 1,
  38023. 4, 2,
  38024. 4, 4,
  38025. 0, 2,
  38026. 1, 1,
  38027. 2, 2,
  38028. 3, 3,
  38029. 1, 3,
  38030. 2, 4 // 23: B + 12
  38031. ];
  38032. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38033. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38034. // First island of uv mapping
  38035. // v = 4h 3+ 2
  38036. // v = 3h 9+ 4
  38037. // v = 2h 9+ 5 B
  38038. // v = 1h 9 1 0
  38039. // v = 0h 3 8 7 A
  38040. // u = 0 1 2 3 4 5 6 *a
  38041. // Second island of uv mapping
  38042. // v = 4h 0+ B+ 4+
  38043. // v = 3h A+ 2+
  38044. // v = 2h 7+ 6 3+
  38045. // v = 1h 8+ 3+
  38046. // v = 0h
  38047. // u = 0 1 2 3 4 5 6 *a
  38048. // Face layout on texture UV mapping
  38049. // ============
  38050. // \ 4 /\ 16 / ======
  38051. // \ / \ / /\ 11 /
  38052. // \/ 7 \/ / \ /
  38053. // ======= / 10 \/
  38054. // /\ 17 /\ =======
  38055. // / \ / \ \ 15 /\
  38056. // / 8 \/ 12 \ \ / \
  38057. // ============ \/ 6 \
  38058. // \ 18 /\ ============
  38059. // \ / \ \ 5 /\ 0 /
  38060. // \/ 13 \ \ / \ /
  38061. // ======= \/ 1 \/
  38062. // =============
  38063. // /\ 19 /\ 2 /\
  38064. // / \ / \ / \
  38065. // / 14 \/ 9 \/ 3 \
  38066. // ===================
  38067. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38068. var ustep = 138 / 1024;
  38069. var vstep = 239 / 1024;
  38070. var uoffset = 60 / 1024;
  38071. var voffset = 26 / 1024;
  38072. // Second island should have margin, not to touch the first island
  38073. // avoid any borderline artefact in pixel rounding
  38074. var island_u_offset = -40 / 1024;
  38075. var island_v_offset = +20 / 1024;
  38076. // face is either island 0 or 1 :
  38077. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38078. var island = [
  38079. 0, 0, 0, 0, 1,
  38080. 0, 0, 1, 1, 0,
  38081. 0, 0, 1, 1, 0,
  38082. 0, 1, 1, 1, 0 // 15 - 19
  38083. ];
  38084. var indices = new Array();
  38085. var positions = new Array();
  38086. var normals = new Array();
  38087. var uvs = new Array();
  38088. var current_indice = 0;
  38089. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38090. var face_vertex_pos = new Array(3);
  38091. var face_vertex_uv = new Array(3);
  38092. var v012;
  38093. for (v012 = 0; v012 < 3; v012++) {
  38094. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38095. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38096. }
  38097. // create all with normals
  38098. for (var face = 0; face < 20; face++) {
  38099. // 3 vertex per face
  38100. for (v012 = 0; v012 < 3; v012++) {
  38101. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38102. var v_id = ico_indices[3 * face + v012];
  38103. // vertex have 3D position (x,y,z)
  38104. 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]);
  38105. // Normalize to get normal, then scale to radius
  38106. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38107. // uv Coordinates from vertex ID
  38108. 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);
  38109. }
  38110. // Subdivide the face (interpolate pos, norm, uv)
  38111. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38112. // - norm is linear interpolation of vertex corner normal
  38113. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38114. // - uv is linear interpolation
  38115. //
  38116. // Topology is as below for sub-divide by 2
  38117. // vertex shown as v0,v1,v2
  38118. // interp index is i1 to progress in range [v0,v1[
  38119. // interp index is i2 to progress in range [v0,v2[
  38120. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38121. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38122. //
  38123. //
  38124. // i2 v2
  38125. // ^ ^
  38126. // / / \
  38127. // / / \
  38128. // / / \
  38129. // / / (0,1) \
  38130. // / #---------\
  38131. // / / \ (0,0)'/ \
  38132. // / / \ / \
  38133. // / / \ / \
  38134. // / / (0,0) \ / (1,0) \
  38135. // / #---------#---------\
  38136. // v0 v1
  38137. //
  38138. // --------------------> i1
  38139. //
  38140. // interp of (i1,i2):
  38141. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38142. // along i1 : lerp(x0,x1, i1/(S-i2))
  38143. //
  38144. // centroid of triangle is needed to get help normal computation
  38145. // (c1,c2) are used for centroid location
  38146. var interp_vertex = function (i1, i2, c1, c2) {
  38147. // vertex is interpolated from
  38148. // - face_vertex_pos[0..2]
  38149. // - face_vertex_uv[0..2]
  38150. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38151. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38152. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38153. pos_interp.normalize();
  38154. var vertex_normal;
  38155. if (flat) {
  38156. // in flat mode, recalculate normal as face centroid normal
  38157. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38158. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38159. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38160. }
  38161. else {
  38162. // in smooth mode, recalculate normal from each single vertex position
  38163. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38164. }
  38165. // Vertex normal need correction due to X,Y,Z radius scaling
  38166. vertex_normal.x /= radiusX;
  38167. vertex_normal.y /= radiusY;
  38168. vertex_normal.z /= radiusZ;
  38169. vertex_normal.normalize();
  38170. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38171. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38172. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38173. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38174. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38175. uvs.push(uv_interp.x, uv_interp.y);
  38176. // push each vertex has member of a face
  38177. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38178. indices.push(current_indice);
  38179. current_indice++;
  38180. };
  38181. for (var i2 = 0; i2 < subdivisions; i2++) {
  38182. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38183. // face : (i1,i2) for /\ :
  38184. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38185. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38186. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38187. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38188. if (i1 + i2 + 1 < subdivisions) {
  38189. // face : (i1,i2)' for \/ :
  38190. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38191. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38192. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38193. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38194. }
  38195. }
  38196. }
  38197. }
  38198. // Sides
  38199. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38200. // Result
  38201. var vertexData = new VertexData();
  38202. vertexData.indices = indices;
  38203. vertexData.positions = positions;
  38204. vertexData.normals = normals;
  38205. vertexData.uvs = uvs;
  38206. return vertexData;
  38207. };
  38208. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38209. /**
  38210. * Creates the VertexData for a Polyhedron
  38211. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38212. * * type provided types are:
  38213. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38214. * * 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)
  38215. * * size the size of the IcoSphere, optional default 1
  38216. * * sizeX allows stretching in the x direction, optional, default size
  38217. * * sizeY allows stretching in the y direction, optional, default size
  38218. * * sizeZ allows stretching in the z direction, optional, default size
  38219. * * 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
  38220. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38221. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38222. * * flat when true creates a flat shaded mesh, optional, default true
  38223. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38224. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38225. * * 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)
  38226. * * 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)
  38227. * @returns the VertexData of the Polyhedron
  38228. */
  38229. VertexData.CreatePolyhedron = function (options) {
  38230. // provided polyhedron types :
  38231. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38232. // 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)
  38233. var polyhedra = [];
  38234. 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]] };
  38235. 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]] };
  38236. polyhedra[2] = {
  38237. 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]],
  38238. 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]]
  38239. };
  38240. polyhedra[3] = {
  38241. 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]],
  38242. 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]]
  38243. };
  38244. polyhedra[4] = {
  38245. 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]],
  38246. 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]]
  38247. };
  38248. 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]] };
  38249. 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]] };
  38250. 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]] };
  38251. 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]] };
  38252. 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]] };
  38253. 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]] };
  38254. 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]] };
  38255. 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]] };
  38256. 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]] };
  38257. polyhedra[14] = {
  38258. 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]],
  38259. 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]]
  38260. };
  38261. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38262. var size = options.size;
  38263. var sizeX = options.sizeX || size || 1;
  38264. var sizeY = options.sizeY || size || 1;
  38265. var sizeZ = options.sizeZ || size || 1;
  38266. var data = options.custom || polyhedra[type];
  38267. var nbfaces = data.face.length;
  38268. var faceUV = options.faceUV || new Array(nbfaces);
  38269. var faceColors = options.faceColors;
  38270. var flat = (options.flat === undefined) ? true : options.flat;
  38271. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38272. var positions = new Array();
  38273. var indices = new Array();
  38274. var normals = new Array();
  38275. var uvs = new Array();
  38276. var colors = new Array();
  38277. var index = 0;
  38278. var faceIdx = 0; // face cursor in the array "indexes"
  38279. var indexes = new Array();
  38280. var i = 0;
  38281. var f = 0;
  38282. var u, v, ang, x, y, tmp;
  38283. // default face colors and UV if undefined
  38284. if (flat) {
  38285. for (f = 0; f < nbfaces; f++) {
  38286. if (faceColors && faceColors[f] === undefined) {
  38287. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38288. }
  38289. if (faceUV && faceUV[f] === undefined) {
  38290. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38291. }
  38292. }
  38293. }
  38294. if (!flat) {
  38295. for (i = 0; i < data.vertex.length; i++) {
  38296. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38297. uvs.push(0, 0);
  38298. }
  38299. for (f = 0; f < nbfaces; f++) {
  38300. for (i = 0; i < data.face[f].length - 2; i++) {
  38301. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38302. }
  38303. }
  38304. }
  38305. else {
  38306. for (f = 0; f < nbfaces; f++) {
  38307. var fl = data.face[f].length; // number of vertices of the current face
  38308. ang = 2 * Math.PI / fl;
  38309. x = 0.5 * Math.tan(ang / 2);
  38310. y = 0.5;
  38311. // positions, uvs, colors
  38312. for (i = 0; i < fl; i++) {
  38313. // positions
  38314. 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);
  38315. indexes.push(index);
  38316. index++;
  38317. // uvs
  38318. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38319. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38320. uvs.push(u, v);
  38321. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38322. y = x * Math.sin(ang) + y * Math.cos(ang);
  38323. x = tmp;
  38324. // colors
  38325. if (faceColors) {
  38326. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38327. }
  38328. }
  38329. // indices from indexes
  38330. for (i = 0; i < fl - 2; i++) {
  38331. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38332. }
  38333. faceIdx += fl;
  38334. }
  38335. }
  38336. VertexData.ComputeNormals(positions, indices, normals);
  38337. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38338. var vertexData = new VertexData();
  38339. vertexData.positions = positions;
  38340. vertexData.indices = indices;
  38341. vertexData.normals = normals;
  38342. vertexData.uvs = uvs;
  38343. if (faceColors && flat) {
  38344. vertexData.colors = colors;
  38345. }
  38346. return vertexData;
  38347. };
  38348. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38349. /**
  38350. * Creates the VertexData for a TorusKnot
  38351. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38352. * * radius the radius of the torus knot, optional, default 2
  38353. * * tube the thickness of the tube, optional, default 0.5
  38354. * * radialSegments the number of sides on each tube segments, optional, default 32
  38355. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38356. * * p the number of windings around the z axis, optional, default 2
  38357. * * q the number of windings around the x axis, optional, default 3
  38358. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38359. * * 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)
  38360. * * 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)
  38361. * @returns the VertexData of the Torus Knot
  38362. */
  38363. VertexData.CreateTorusKnot = function (options) {
  38364. var indices = new Array();
  38365. var positions = new Array();
  38366. var normals = new Array();
  38367. var uvs = new Array();
  38368. var radius = options.radius || 2;
  38369. var tube = options.tube || 0.5;
  38370. var radialSegments = options.radialSegments || 32;
  38371. var tubularSegments = options.tubularSegments || 32;
  38372. var p = options.p || 2;
  38373. var q = options.q || 3;
  38374. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38375. // Helper
  38376. var getPos = function (angle) {
  38377. var cu = Math.cos(angle);
  38378. var su = Math.sin(angle);
  38379. var quOverP = q / p * angle;
  38380. var cs = Math.cos(quOverP);
  38381. var tx = radius * (2 + cs) * 0.5 * cu;
  38382. var ty = radius * (2 + cs) * su * 0.5;
  38383. var tz = radius * Math.sin(quOverP) * 0.5;
  38384. return new BABYLON.Vector3(tx, ty, tz);
  38385. };
  38386. // Vertices
  38387. var i;
  38388. var j;
  38389. for (i = 0; i <= radialSegments; i++) {
  38390. var modI = i % radialSegments;
  38391. var u = modI / radialSegments * 2 * p * Math.PI;
  38392. var p1 = getPos(u);
  38393. var p2 = getPos(u + 0.01);
  38394. var tang = p2.subtract(p1);
  38395. var n = p2.add(p1);
  38396. var bitan = BABYLON.Vector3.Cross(tang, n);
  38397. n = BABYLON.Vector3.Cross(bitan, tang);
  38398. bitan.normalize();
  38399. n.normalize();
  38400. for (j = 0; j < tubularSegments; j++) {
  38401. var modJ = j % tubularSegments;
  38402. var v = modJ / tubularSegments * 2 * Math.PI;
  38403. var cx = -tube * Math.cos(v);
  38404. var cy = tube * Math.sin(v);
  38405. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38406. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38407. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38408. uvs.push(i / radialSegments);
  38409. uvs.push(j / tubularSegments);
  38410. }
  38411. }
  38412. for (i = 0; i < radialSegments; i++) {
  38413. for (j = 0; j < tubularSegments; j++) {
  38414. var jNext = (j + 1) % tubularSegments;
  38415. var a = i * tubularSegments + j;
  38416. var b = (i + 1) * tubularSegments + j;
  38417. var c = (i + 1) * tubularSegments + jNext;
  38418. var d = i * tubularSegments + jNext;
  38419. indices.push(d);
  38420. indices.push(b);
  38421. indices.push(a);
  38422. indices.push(d);
  38423. indices.push(c);
  38424. indices.push(b);
  38425. }
  38426. }
  38427. // Normals
  38428. VertexData.ComputeNormals(positions, indices, normals);
  38429. // Sides
  38430. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38431. // Result
  38432. var vertexData = new VertexData();
  38433. vertexData.indices = indices;
  38434. vertexData.positions = positions;
  38435. vertexData.normals = normals;
  38436. vertexData.uvs = uvs;
  38437. return vertexData;
  38438. };
  38439. // Tools
  38440. /**
  38441. * Compute normals for given positions and indices
  38442. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38443. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38444. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38445. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38446. * * facetNormals : optional array of facet normals (vector3)
  38447. * * facetPositions : optional array of facet positions (vector3)
  38448. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38449. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38450. * * bInfo : optional bounding info, required for facetPartitioning computation
  38451. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38452. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38453. * * useRightHandedSystem: optional boolean to for right handed system computation
  38454. * * depthSort : optional boolean to enable the facet depth sort computation
  38455. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38456. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38457. */
  38458. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38459. // temporary scalar variables
  38460. var index = 0; // facet index
  38461. var p1p2x = 0.0; // p1p2 vector x coordinate
  38462. var p1p2y = 0.0; // p1p2 vector y coordinate
  38463. var p1p2z = 0.0; // p1p2 vector z coordinate
  38464. var p3p2x = 0.0; // p3p2 vector x coordinate
  38465. var p3p2y = 0.0; // p3p2 vector y coordinate
  38466. var p3p2z = 0.0; // p3p2 vector z coordinate
  38467. var faceNormalx = 0.0; // facet normal x coordinate
  38468. var faceNormaly = 0.0; // facet normal y coordinate
  38469. var faceNormalz = 0.0; // facet normal z coordinate
  38470. var length = 0.0; // facet normal length before normalization
  38471. var v1x = 0; // vector1 x index in the positions array
  38472. var v1y = 0; // vector1 y index in the positions array
  38473. var v1z = 0; // vector1 z index in the positions array
  38474. var v2x = 0; // vector2 x index in the positions array
  38475. var v2y = 0; // vector2 y index in the positions array
  38476. var v2z = 0; // vector2 z index in the positions array
  38477. var v3x = 0; // vector3 x index in the positions array
  38478. var v3y = 0; // vector3 y index in the positions array
  38479. var v3z = 0; // vector3 z index in the positions array
  38480. var computeFacetNormals = false;
  38481. var computeFacetPositions = false;
  38482. var computeFacetPartitioning = false;
  38483. var computeDepthSort = false;
  38484. var faceNormalSign = 1;
  38485. var ratio = 0;
  38486. var distanceTo = null;
  38487. if (options) {
  38488. computeFacetNormals = (options.facetNormals) ? true : false;
  38489. computeFacetPositions = (options.facetPositions) ? true : false;
  38490. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38491. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38492. ratio = options.ratio || 0;
  38493. computeDepthSort = (options.depthSort) ? true : false;
  38494. distanceTo = (options.distanceTo);
  38495. if (computeDepthSort) {
  38496. if (distanceTo === undefined) {
  38497. distanceTo = BABYLON.Vector3.Zero();
  38498. }
  38499. var depthSortedFacets = options.depthSortedFacets;
  38500. }
  38501. }
  38502. // facetPartitioning reinit if needed
  38503. var xSubRatio = 0;
  38504. var ySubRatio = 0;
  38505. var zSubRatio = 0;
  38506. var subSq = 0;
  38507. if (computeFacetPartitioning && options && options.bbSize) {
  38508. var ox = 0; // X partitioning index for facet position
  38509. var oy = 0; // Y partinioning index for facet position
  38510. var oz = 0; // Z partinioning index for facet position
  38511. var b1x = 0; // X partitioning index for facet v1 vertex
  38512. var b1y = 0; // Y partitioning index for facet v1 vertex
  38513. var b1z = 0; // z partitioning index for facet v1 vertex
  38514. var b2x = 0; // X partitioning index for facet v2 vertex
  38515. var b2y = 0; // Y partitioning index for facet v2 vertex
  38516. var b2z = 0; // Z partitioning index for facet v2 vertex
  38517. var b3x = 0; // X partitioning index for facet v3 vertex
  38518. var b3y = 0; // Y partitioning index for facet v3 vertex
  38519. var b3z = 0; // Z partitioning index for facet v3 vertex
  38520. var block_idx_o = 0; // facet barycenter block index
  38521. var block_idx_v1 = 0; // v1 vertex block index
  38522. var block_idx_v2 = 0; // v2 vertex block index
  38523. var block_idx_v3 = 0; // v3 vertex block index
  38524. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38525. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38526. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38527. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38528. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38529. subSq = options.subDiv.max * options.subDiv.max;
  38530. options.facetPartitioning.length = 0;
  38531. }
  38532. // reset the normals
  38533. for (index = 0; index < positions.length; index++) {
  38534. normals[index] = 0.0;
  38535. }
  38536. // Loop : 1 indice triplet = 1 facet
  38537. var nbFaces = (indices.length / 3) | 0;
  38538. for (index = 0; index < nbFaces; index++) {
  38539. // get the indexes of the coordinates of each vertex of the facet
  38540. v1x = indices[index * 3] * 3;
  38541. v1y = v1x + 1;
  38542. v1z = v1x + 2;
  38543. v2x = indices[index * 3 + 1] * 3;
  38544. v2y = v2x + 1;
  38545. v2z = v2x + 2;
  38546. v3x = indices[index * 3 + 2] * 3;
  38547. v3y = v3x + 1;
  38548. v3z = v3x + 2;
  38549. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38550. p1p2y = positions[v1y] - positions[v2y];
  38551. p1p2z = positions[v1z] - positions[v2z];
  38552. p3p2x = positions[v3x] - positions[v2x];
  38553. p3p2y = positions[v3y] - positions[v2y];
  38554. p3p2z = positions[v3z] - positions[v2z];
  38555. // compute the face normal with the cross product
  38556. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38557. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38558. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38559. // normalize this normal and store it in the array facetData
  38560. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38561. length = (length === 0) ? 1.0 : length;
  38562. faceNormalx /= length;
  38563. faceNormaly /= length;
  38564. faceNormalz /= length;
  38565. if (computeFacetNormals && options) {
  38566. options.facetNormals[index].x = faceNormalx;
  38567. options.facetNormals[index].y = faceNormaly;
  38568. options.facetNormals[index].z = faceNormalz;
  38569. }
  38570. if (computeFacetPositions && options) {
  38571. // compute and the facet barycenter coordinates in the array facetPositions
  38572. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38573. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38574. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38575. }
  38576. if (computeFacetPartitioning && options) {
  38577. // store the facet indexes in arrays in the main facetPartitioning array :
  38578. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38579. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38580. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38581. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38582. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38583. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38584. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38585. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38586. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38587. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38588. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38589. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38590. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38591. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38592. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38593. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38594. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38595. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38596. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38597. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38598. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38599. // push each facet index in each block containing the vertex
  38600. options.facetPartitioning[block_idx_v1].push(index);
  38601. if (block_idx_v2 != block_idx_v1) {
  38602. options.facetPartitioning[block_idx_v2].push(index);
  38603. }
  38604. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38605. options.facetPartitioning[block_idx_v3].push(index);
  38606. }
  38607. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38608. options.facetPartitioning[block_idx_o].push(index);
  38609. }
  38610. }
  38611. if (computeDepthSort && options && options.facetPositions) {
  38612. var dsf = depthSortedFacets[index];
  38613. dsf.ind = index * 3;
  38614. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38615. }
  38616. // compute the normals anyway
  38617. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38618. normals[v1y] += faceNormaly;
  38619. normals[v1z] += faceNormalz;
  38620. normals[v2x] += faceNormalx;
  38621. normals[v2y] += faceNormaly;
  38622. normals[v2z] += faceNormalz;
  38623. normals[v3x] += faceNormalx;
  38624. normals[v3y] += faceNormaly;
  38625. normals[v3z] += faceNormalz;
  38626. }
  38627. // last normalization of each normal
  38628. for (index = 0; index < normals.length / 3; index++) {
  38629. faceNormalx = normals[index * 3];
  38630. faceNormaly = normals[index * 3 + 1];
  38631. faceNormalz = normals[index * 3 + 2];
  38632. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38633. length = (length === 0) ? 1.0 : length;
  38634. faceNormalx /= length;
  38635. faceNormaly /= length;
  38636. faceNormalz /= length;
  38637. normals[index * 3] = faceNormalx;
  38638. normals[index * 3 + 1] = faceNormaly;
  38639. normals[index * 3 + 2] = faceNormalz;
  38640. }
  38641. };
  38642. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38643. var li = indices.length;
  38644. var ln = normals.length;
  38645. var i;
  38646. var n;
  38647. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38648. switch (sideOrientation) {
  38649. case BABYLON.Mesh.FRONTSIDE:
  38650. // nothing changed
  38651. break;
  38652. case BABYLON.Mesh.BACKSIDE:
  38653. var tmp;
  38654. // indices
  38655. for (i = 0; i < li; i += 3) {
  38656. tmp = indices[i];
  38657. indices[i] = indices[i + 2];
  38658. indices[i + 2] = tmp;
  38659. }
  38660. // normals
  38661. for (n = 0; n < ln; n++) {
  38662. normals[n] = -normals[n];
  38663. }
  38664. break;
  38665. case BABYLON.Mesh.DOUBLESIDE:
  38666. // positions
  38667. var lp = positions.length;
  38668. var l = lp / 3;
  38669. for (var p = 0; p < lp; p++) {
  38670. positions[lp + p] = positions[p];
  38671. }
  38672. // indices
  38673. for (i = 0; i < li; i += 3) {
  38674. indices[i + li] = indices[i + 2] + l;
  38675. indices[i + 1 + li] = indices[i + 1] + l;
  38676. indices[i + 2 + li] = indices[i] + l;
  38677. }
  38678. // normals
  38679. for (n = 0; n < ln; n++) {
  38680. normals[ln + n] = -normals[n];
  38681. }
  38682. // uvs
  38683. var lu = uvs.length;
  38684. var u = 0;
  38685. for (u = 0; u < lu; u++) {
  38686. uvs[u + lu] = uvs[u];
  38687. }
  38688. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38689. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38690. u = 0;
  38691. for (i = 0; i < lu / 2; i++) {
  38692. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38693. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38694. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38695. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38696. u += 2;
  38697. }
  38698. break;
  38699. }
  38700. };
  38701. /**
  38702. * Applies VertexData created from the imported parameters to the geometry
  38703. * @param parsedVertexData the parsed data from an imported file
  38704. * @param geometry the geometry to apply the VertexData to
  38705. */
  38706. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38707. var vertexData = new VertexData();
  38708. // positions
  38709. var positions = parsedVertexData.positions;
  38710. if (positions) {
  38711. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38712. }
  38713. // normals
  38714. var normals = parsedVertexData.normals;
  38715. if (normals) {
  38716. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38717. }
  38718. // tangents
  38719. var tangents = parsedVertexData.tangents;
  38720. if (tangents) {
  38721. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38722. }
  38723. // uvs
  38724. var uvs = parsedVertexData.uvs;
  38725. if (uvs) {
  38726. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38727. }
  38728. // uv2s
  38729. var uv2s = parsedVertexData.uv2s;
  38730. if (uv2s) {
  38731. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38732. }
  38733. // uv3s
  38734. var uv3s = parsedVertexData.uv3s;
  38735. if (uv3s) {
  38736. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38737. }
  38738. // uv4s
  38739. var uv4s = parsedVertexData.uv4s;
  38740. if (uv4s) {
  38741. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38742. }
  38743. // uv5s
  38744. var uv5s = parsedVertexData.uv5s;
  38745. if (uv5s) {
  38746. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38747. }
  38748. // uv6s
  38749. var uv6s = parsedVertexData.uv6s;
  38750. if (uv6s) {
  38751. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38752. }
  38753. // colors
  38754. var colors = parsedVertexData.colors;
  38755. if (colors) {
  38756. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38757. }
  38758. // matricesIndices
  38759. var matricesIndices = parsedVertexData.matricesIndices;
  38760. if (matricesIndices) {
  38761. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38762. }
  38763. // matricesWeights
  38764. var matricesWeights = parsedVertexData.matricesWeights;
  38765. if (matricesWeights) {
  38766. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38767. }
  38768. // indices
  38769. var indices = parsedVertexData.indices;
  38770. if (indices) {
  38771. vertexData.indices = indices;
  38772. }
  38773. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38774. };
  38775. return VertexData;
  38776. }());
  38777. BABYLON.VertexData = VertexData;
  38778. })(BABYLON || (BABYLON = {}));
  38779. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38780. var BABYLON;
  38781. (function (BABYLON) {
  38782. /**
  38783. * Class used to store geometry data (vertex buffers + index buffer)
  38784. */
  38785. var Geometry = /** @class */ (function () {
  38786. /**
  38787. * Creates a new geometry
  38788. * @param id defines the unique ID
  38789. * @param scene defines the hosting scene
  38790. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38791. * @param updatable defines if geometry must be updatable (false by default)
  38792. * @param mesh defines the mesh that will be associated with the geometry
  38793. */
  38794. function Geometry(id, scene, vertexData, updatable, mesh) {
  38795. if (updatable === void 0) { updatable = false; }
  38796. if (mesh === void 0) { mesh = null; }
  38797. /**
  38798. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38799. */
  38800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38801. this._totalVertices = 0;
  38802. this._isDisposed = false;
  38803. this._indexBufferIsUpdatable = false;
  38804. this.id = id;
  38805. this._engine = scene.getEngine();
  38806. this._meshes = [];
  38807. this._scene = scene;
  38808. //Init vertex buffer cache
  38809. this._vertexBuffers = {};
  38810. this._indices = [];
  38811. this._updatable = updatable;
  38812. // vertexData
  38813. if (vertexData) {
  38814. this.setAllVerticesData(vertexData, updatable);
  38815. }
  38816. else {
  38817. this._totalVertices = 0;
  38818. this._indices = [];
  38819. }
  38820. if (this._engine.getCaps().vertexArrayObject) {
  38821. this._vertexArrayObjects = {};
  38822. }
  38823. // applyToMesh
  38824. if (mesh) {
  38825. if (mesh.getClassName() === "LinesMesh") {
  38826. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38827. this._updateExtend();
  38828. }
  38829. this.applyToMesh(mesh);
  38830. mesh.computeWorldMatrix(true);
  38831. }
  38832. }
  38833. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38834. /**
  38835. * 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
  38836. */
  38837. get: function () {
  38838. return this._boundingBias;
  38839. },
  38840. /**
  38841. * 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
  38842. */
  38843. set: function (value) {
  38844. if (this._boundingBias && this._boundingBias.equals(value)) {
  38845. return;
  38846. }
  38847. this._boundingBias = value.clone();
  38848. this._updateBoundingInfo(true, null);
  38849. },
  38850. enumerable: true,
  38851. configurable: true
  38852. });
  38853. /**
  38854. * Static function used to attach a new empty geometry to a mesh
  38855. * @param mesh defines the mesh to attach the geometry to
  38856. * @returns the new {BABYLON.Geometry}
  38857. */
  38858. Geometry.CreateGeometryForMesh = function (mesh) {
  38859. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38860. geometry.applyToMesh(mesh);
  38861. return geometry;
  38862. };
  38863. Object.defineProperty(Geometry.prototype, "extend", {
  38864. /**
  38865. * Gets the current extend of the geometry
  38866. */
  38867. get: function () {
  38868. return this._extend;
  38869. },
  38870. enumerable: true,
  38871. configurable: true
  38872. });
  38873. /**
  38874. * Gets the hosting scene
  38875. * @returns the hosting {BABYLON.Scene}
  38876. */
  38877. Geometry.prototype.getScene = function () {
  38878. return this._scene;
  38879. };
  38880. /**
  38881. * Gets the hosting engine
  38882. * @returns the hosting {BABYLON.Engine}
  38883. */
  38884. Geometry.prototype.getEngine = function () {
  38885. return this._engine;
  38886. };
  38887. /**
  38888. * Defines if the geometry is ready to use
  38889. * @returns true if the geometry is ready to be used
  38890. */
  38891. Geometry.prototype.isReady = function () {
  38892. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38893. };
  38894. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38895. /**
  38896. * Gets a value indicating that the geometry should not be serialized
  38897. */
  38898. get: function () {
  38899. for (var index = 0; index < this._meshes.length; index++) {
  38900. if (!this._meshes[index].doNotSerialize) {
  38901. return false;
  38902. }
  38903. }
  38904. return true;
  38905. },
  38906. enumerable: true,
  38907. configurable: true
  38908. });
  38909. /** @hidden */
  38910. Geometry.prototype._rebuild = function () {
  38911. if (this._vertexArrayObjects) {
  38912. this._vertexArrayObjects = {};
  38913. }
  38914. // Index buffer
  38915. if (this._meshes.length !== 0 && this._indices) {
  38916. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38917. }
  38918. // Vertex buffers
  38919. for (var key in this._vertexBuffers) {
  38920. var vertexBuffer = this._vertexBuffers[key];
  38921. vertexBuffer._rebuild();
  38922. }
  38923. };
  38924. /**
  38925. * Affects all gemetry data in one call
  38926. * @param vertexData defines the geometry data
  38927. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38928. */
  38929. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38930. vertexData.applyToGeometry(this, updatable);
  38931. this.notifyUpdate();
  38932. };
  38933. /**
  38934. * Set specific vertex data
  38935. * @param kind defines the data kind (Position, normal, etc...)
  38936. * @param data defines the vertex data to use
  38937. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38938. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38939. */
  38940. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38941. if (updatable === void 0) { updatable = false; }
  38942. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38943. this.setVerticesBuffer(buffer);
  38944. };
  38945. /**
  38946. * Removes a specific vertex data
  38947. * @param kind defines the data kind (Position, normal, etc...)
  38948. */
  38949. Geometry.prototype.removeVerticesData = function (kind) {
  38950. if (this._vertexBuffers[kind]) {
  38951. this._vertexBuffers[kind].dispose();
  38952. delete this._vertexBuffers[kind];
  38953. }
  38954. };
  38955. /**
  38956. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38957. * @param buffer defines the vertex buffer to use
  38958. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38959. */
  38960. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38961. if (totalVertices === void 0) { totalVertices = null; }
  38962. var kind = buffer.getKind();
  38963. if (this._vertexBuffers[kind]) {
  38964. this._vertexBuffers[kind].dispose();
  38965. }
  38966. this._vertexBuffers[kind] = buffer;
  38967. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38968. var data = buffer.getData();
  38969. if (totalVertices != null) {
  38970. this._totalVertices = totalVertices;
  38971. }
  38972. else {
  38973. if (data != null) {
  38974. this._totalVertices = data.length / (buffer.byteStride / 4);
  38975. }
  38976. }
  38977. this._updateExtend(data);
  38978. this._resetPointsArrayCache();
  38979. var meshes = this._meshes;
  38980. var numOfMeshes = meshes.length;
  38981. for (var index = 0; index < numOfMeshes; index++) {
  38982. var mesh = meshes[index];
  38983. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38984. mesh._createGlobalSubMesh(false);
  38985. mesh.computeWorldMatrix(true);
  38986. }
  38987. }
  38988. this.notifyUpdate(kind);
  38989. if (this._vertexArrayObjects) {
  38990. this._disposeVertexArrayObjects();
  38991. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38992. }
  38993. };
  38994. /**
  38995. * Update a specific vertex buffer
  38996. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38997. * It will do nothing if the buffer is not updatable
  38998. * @param kind defines the data kind (Position, normal, etc...)
  38999. * @param data defines the data to use
  39000. * @param offset defines the offset in the target buffer where to store the data
  39001. * @param useBytes set to true if the offset is in bytes
  39002. */
  39003. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39004. if (useBytes === void 0) { useBytes = false; }
  39005. var vertexBuffer = this.getVertexBuffer(kind);
  39006. if (!vertexBuffer) {
  39007. return;
  39008. }
  39009. vertexBuffer.updateDirectly(data, offset, useBytes);
  39010. this.notifyUpdate(kind);
  39011. };
  39012. /**
  39013. * Update a specific vertex buffer
  39014. * This function will create a new buffer if the current one is not updatable
  39015. * @param kind defines the data kind (Position, normal, etc...)
  39016. * @param data defines the data to use
  39017. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39018. */
  39019. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39020. if (updateExtends === void 0) { updateExtends = false; }
  39021. var vertexBuffer = this.getVertexBuffer(kind);
  39022. if (!vertexBuffer) {
  39023. return;
  39024. }
  39025. vertexBuffer.update(data);
  39026. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39027. this._updateBoundingInfo(updateExtends, data);
  39028. }
  39029. this.notifyUpdate(kind);
  39030. };
  39031. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39032. if (updateExtends) {
  39033. this._updateExtend(data);
  39034. }
  39035. var meshes = this._meshes;
  39036. var numOfMeshes = meshes.length;
  39037. this._resetPointsArrayCache();
  39038. for (var index = 0; index < numOfMeshes; index++) {
  39039. var mesh = meshes[index];
  39040. if (updateExtends) {
  39041. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39042. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39043. var subMesh = mesh.subMeshes[subIndex];
  39044. subMesh.refreshBoundingInfo();
  39045. }
  39046. }
  39047. }
  39048. };
  39049. /** @hidden */
  39050. Geometry.prototype._bind = function (effect, indexToBind) {
  39051. if (!effect) {
  39052. return;
  39053. }
  39054. if (indexToBind === undefined) {
  39055. indexToBind = this._indexBuffer;
  39056. }
  39057. var vbs = this.getVertexBuffers();
  39058. if (!vbs) {
  39059. return;
  39060. }
  39061. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39062. this._engine.bindBuffers(vbs, indexToBind, effect);
  39063. return;
  39064. }
  39065. // Using VAO
  39066. if (!this._vertexArrayObjects[effect.key]) {
  39067. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39068. }
  39069. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39070. };
  39071. /**
  39072. * Gets total number of vertices
  39073. * @returns the total number of vertices
  39074. */
  39075. Geometry.prototype.getTotalVertices = function () {
  39076. if (!this.isReady()) {
  39077. return 0;
  39078. }
  39079. return this._totalVertices;
  39080. };
  39081. /**
  39082. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39083. * @param kind defines the data kind (Position, normal, etc...)
  39084. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39085. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39086. * @returns a float array containing vertex data
  39087. */
  39088. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39089. var vertexBuffer = this.getVertexBuffer(kind);
  39090. if (!vertexBuffer) {
  39091. return null;
  39092. }
  39093. var data = vertexBuffer.getData();
  39094. if (!data) {
  39095. return null;
  39096. }
  39097. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39098. var count = this._totalVertices * vertexBuffer.getSize();
  39099. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39100. var copy_1 = new Array(count);
  39101. vertexBuffer.forEach(count, function (value, index) {
  39102. copy_1[index] = value;
  39103. });
  39104. return copy_1;
  39105. }
  39106. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39107. if (data instanceof Array) {
  39108. var offset = vertexBuffer.byteOffset / 4;
  39109. return BABYLON.Tools.Slice(data, offset, offset + count);
  39110. }
  39111. else if (data instanceof ArrayBuffer) {
  39112. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39113. }
  39114. else {
  39115. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39116. }
  39117. }
  39118. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39119. return BABYLON.Tools.Slice(data);
  39120. }
  39121. return data;
  39122. };
  39123. /**
  39124. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39125. * @param kind defines the data kind (Position, normal, etc...)
  39126. * @returns true if the vertex buffer with the specified kind is updatable
  39127. */
  39128. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39129. var vb = this._vertexBuffers[kind];
  39130. if (!vb) {
  39131. return false;
  39132. }
  39133. return vb.isUpdatable();
  39134. };
  39135. /**
  39136. * Gets a specific vertex buffer
  39137. * @param kind defines the data kind (Position, normal, etc...)
  39138. * @returns a {BABYLON.VertexBuffer}
  39139. */
  39140. Geometry.prototype.getVertexBuffer = function (kind) {
  39141. if (!this.isReady()) {
  39142. return null;
  39143. }
  39144. return this._vertexBuffers[kind];
  39145. };
  39146. /**
  39147. * Returns all vertex buffers
  39148. * @return an object holding all vertex buffers indexed by kind
  39149. */
  39150. Geometry.prototype.getVertexBuffers = function () {
  39151. if (!this.isReady()) {
  39152. return null;
  39153. }
  39154. return this._vertexBuffers;
  39155. };
  39156. /**
  39157. * Gets a boolean indicating if specific vertex buffer is present
  39158. * @param kind defines the data kind (Position, normal, etc...)
  39159. * @returns true if data is present
  39160. */
  39161. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39162. if (!this._vertexBuffers) {
  39163. if (this._delayInfo) {
  39164. return this._delayInfo.indexOf(kind) !== -1;
  39165. }
  39166. return false;
  39167. }
  39168. return this._vertexBuffers[kind] !== undefined;
  39169. };
  39170. /**
  39171. * Gets a list of all attached data kinds (Position, normal, etc...)
  39172. * @returns a list of string containing all kinds
  39173. */
  39174. Geometry.prototype.getVerticesDataKinds = function () {
  39175. var result = [];
  39176. var kind;
  39177. if (!this._vertexBuffers && this._delayInfo) {
  39178. for (kind in this._delayInfo) {
  39179. result.push(kind);
  39180. }
  39181. }
  39182. else {
  39183. for (kind in this._vertexBuffers) {
  39184. result.push(kind);
  39185. }
  39186. }
  39187. return result;
  39188. };
  39189. /**
  39190. * Update index buffer
  39191. * @param indices defines the indices to store in the index buffer
  39192. * @param offset defines the offset in the target buffer where to store the data
  39193. */
  39194. Geometry.prototype.updateIndices = function (indices, offset) {
  39195. if (!this._indexBuffer) {
  39196. return;
  39197. }
  39198. if (!this._indexBufferIsUpdatable) {
  39199. this.setIndices(indices, null, true);
  39200. }
  39201. else {
  39202. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39203. }
  39204. };
  39205. /**
  39206. * Creates a new index buffer
  39207. * @param indices defines the indices to store in the index buffer
  39208. * @param totalVertices defines the total number of vertices (could be null)
  39209. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39210. */
  39211. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39212. if (totalVertices === void 0) { totalVertices = null; }
  39213. if (updatable === void 0) { updatable = false; }
  39214. if (this._indexBuffer) {
  39215. this._engine._releaseBuffer(this._indexBuffer);
  39216. }
  39217. this._disposeVertexArrayObjects();
  39218. this._indices = indices;
  39219. this._indexBufferIsUpdatable = updatable;
  39220. if (this._meshes.length !== 0 && this._indices) {
  39221. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39222. }
  39223. if (totalVertices != undefined) { // including null and undefined
  39224. this._totalVertices = totalVertices;
  39225. }
  39226. var meshes = this._meshes;
  39227. var numOfMeshes = meshes.length;
  39228. for (var index = 0; index < numOfMeshes; index++) {
  39229. meshes[index]._createGlobalSubMesh(true);
  39230. }
  39231. this.notifyUpdate();
  39232. };
  39233. /**
  39234. * Return the total number of indices
  39235. * @returns the total number of indices
  39236. */
  39237. Geometry.prototype.getTotalIndices = function () {
  39238. if (!this.isReady()) {
  39239. return 0;
  39240. }
  39241. return this._indices.length;
  39242. };
  39243. /**
  39244. * Gets the index buffer array
  39245. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39246. * @returns the index buffer array
  39247. */
  39248. Geometry.prototype.getIndices = function (copyWhenShared) {
  39249. if (!this.isReady()) {
  39250. return null;
  39251. }
  39252. var orig = this._indices;
  39253. if (!copyWhenShared || this._meshes.length === 1) {
  39254. return orig;
  39255. }
  39256. else {
  39257. var len = orig.length;
  39258. var copy = [];
  39259. for (var i = 0; i < len; i++) {
  39260. copy.push(orig[i]);
  39261. }
  39262. return copy;
  39263. }
  39264. };
  39265. /**
  39266. * Gets the index buffer
  39267. * @return the index buffer
  39268. */
  39269. Geometry.prototype.getIndexBuffer = function () {
  39270. if (!this.isReady()) {
  39271. return null;
  39272. }
  39273. return this._indexBuffer;
  39274. };
  39275. /** @hidden */
  39276. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39277. if (effect === void 0) { effect = null; }
  39278. if (!effect || !this._vertexArrayObjects) {
  39279. return;
  39280. }
  39281. if (this._vertexArrayObjects[effect.key]) {
  39282. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39283. delete this._vertexArrayObjects[effect.key];
  39284. }
  39285. };
  39286. /**
  39287. * Release the associated resources for a specific mesh
  39288. * @param mesh defines the source mesh
  39289. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39290. */
  39291. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39292. var meshes = this._meshes;
  39293. var index = meshes.indexOf(mesh);
  39294. if (index === -1) {
  39295. return;
  39296. }
  39297. meshes.splice(index, 1);
  39298. mesh._geometry = null;
  39299. if (meshes.length === 0 && shouldDispose) {
  39300. this.dispose();
  39301. }
  39302. };
  39303. /**
  39304. * Apply current geometry to a given mesh
  39305. * @param mesh defines the mesh to apply geometry to
  39306. */
  39307. Geometry.prototype.applyToMesh = function (mesh) {
  39308. if (mesh._geometry === this) {
  39309. return;
  39310. }
  39311. var previousGeometry = mesh._geometry;
  39312. if (previousGeometry) {
  39313. previousGeometry.releaseForMesh(mesh);
  39314. }
  39315. var meshes = this._meshes;
  39316. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39317. mesh._geometry = this;
  39318. this._scene.pushGeometry(this);
  39319. meshes.push(mesh);
  39320. if (this.isReady()) {
  39321. this._applyToMesh(mesh);
  39322. }
  39323. else {
  39324. mesh._boundingInfo = this._boundingInfo;
  39325. }
  39326. };
  39327. Geometry.prototype._updateExtend = function (data) {
  39328. if (data === void 0) { data = null; }
  39329. if (!data) {
  39330. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39331. }
  39332. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39333. };
  39334. Geometry.prototype._applyToMesh = function (mesh) {
  39335. var numOfMeshes = this._meshes.length;
  39336. // vertexBuffers
  39337. for (var kind in this._vertexBuffers) {
  39338. if (numOfMeshes === 1) {
  39339. this._vertexBuffers[kind].create();
  39340. }
  39341. var buffer = this._vertexBuffers[kind].getBuffer();
  39342. if (buffer)
  39343. buffer.references = numOfMeshes;
  39344. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39345. if (!this._extend) {
  39346. this._updateExtend();
  39347. }
  39348. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39349. mesh._createGlobalSubMesh(false);
  39350. //bounding info was just created again, world matrix should be applied again.
  39351. mesh._updateBoundingInfo();
  39352. }
  39353. }
  39354. // indexBuffer
  39355. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39356. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39357. }
  39358. if (this._indexBuffer) {
  39359. this._indexBuffer.references = numOfMeshes;
  39360. }
  39361. };
  39362. Geometry.prototype.notifyUpdate = function (kind) {
  39363. if (this.onGeometryUpdated) {
  39364. this.onGeometryUpdated(this, kind);
  39365. }
  39366. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39367. var mesh = _a[_i];
  39368. mesh._markSubMeshesAsAttributesDirty();
  39369. }
  39370. };
  39371. /**
  39372. * Load the geometry if it was flagged as delay loaded
  39373. * @param scene defines the hosting scene
  39374. * @param onLoaded defines a callback called when the geometry is loaded
  39375. */
  39376. Geometry.prototype.load = function (scene, onLoaded) {
  39377. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39378. return;
  39379. }
  39380. if (this.isReady()) {
  39381. if (onLoaded) {
  39382. onLoaded();
  39383. }
  39384. return;
  39385. }
  39386. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39387. this._queueLoad(scene, onLoaded);
  39388. };
  39389. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39390. var _this = this;
  39391. if (!this.delayLoadingFile) {
  39392. return;
  39393. }
  39394. scene._addPendingData(this);
  39395. scene._loadFile(this.delayLoadingFile, function (data) {
  39396. if (!_this._delayLoadingFunction) {
  39397. return;
  39398. }
  39399. _this._delayLoadingFunction(JSON.parse(data), _this);
  39400. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39401. _this._delayInfo = [];
  39402. scene._removePendingData(_this);
  39403. var meshes = _this._meshes;
  39404. var numOfMeshes = meshes.length;
  39405. for (var index = 0; index < numOfMeshes; index++) {
  39406. _this._applyToMesh(meshes[index]);
  39407. }
  39408. if (onLoaded) {
  39409. onLoaded();
  39410. }
  39411. }, undefined, true);
  39412. };
  39413. /**
  39414. * Invert the geometry to move from a right handed system to a left handed one.
  39415. */
  39416. Geometry.prototype.toLeftHanded = function () {
  39417. // Flip faces
  39418. var tIndices = this.getIndices(false);
  39419. if (tIndices != null && tIndices.length > 0) {
  39420. for (var i = 0; i < tIndices.length; i += 3) {
  39421. var tTemp = tIndices[i + 0];
  39422. tIndices[i + 0] = tIndices[i + 2];
  39423. tIndices[i + 2] = tTemp;
  39424. }
  39425. this.setIndices(tIndices);
  39426. }
  39427. // Negate position.z
  39428. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39429. if (tPositions != null && tPositions.length > 0) {
  39430. for (var i = 0; i < tPositions.length; i += 3) {
  39431. tPositions[i + 2] = -tPositions[i + 2];
  39432. }
  39433. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39434. }
  39435. // Negate normal.z
  39436. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39437. if (tNormals != null && tNormals.length > 0) {
  39438. for (var i = 0; i < tNormals.length; i += 3) {
  39439. tNormals[i + 2] = -tNormals[i + 2];
  39440. }
  39441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39442. }
  39443. };
  39444. // Cache
  39445. /** @hidden */
  39446. Geometry.prototype._resetPointsArrayCache = function () {
  39447. this._positions = null;
  39448. };
  39449. /** @hidden */
  39450. Geometry.prototype._generatePointsArray = function () {
  39451. if (this._positions)
  39452. return true;
  39453. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39454. if (!data || data.length === 0) {
  39455. return false;
  39456. }
  39457. this._positions = [];
  39458. for (var index = 0; index < data.length; index += 3) {
  39459. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39460. }
  39461. return true;
  39462. };
  39463. /**
  39464. * Gets a value indicating if the geometry is disposed
  39465. * @returns true if the geometry was disposed
  39466. */
  39467. Geometry.prototype.isDisposed = function () {
  39468. return this._isDisposed;
  39469. };
  39470. Geometry.prototype._disposeVertexArrayObjects = function () {
  39471. if (this._vertexArrayObjects) {
  39472. for (var kind in this._vertexArrayObjects) {
  39473. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39474. }
  39475. this._vertexArrayObjects = {};
  39476. }
  39477. };
  39478. /**
  39479. * Free all associated resources
  39480. */
  39481. Geometry.prototype.dispose = function () {
  39482. var meshes = this._meshes;
  39483. var numOfMeshes = meshes.length;
  39484. var index;
  39485. for (index = 0; index < numOfMeshes; index++) {
  39486. this.releaseForMesh(meshes[index]);
  39487. }
  39488. this._meshes = [];
  39489. this._disposeVertexArrayObjects();
  39490. for (var kind in this._vertexBuffers) {
  39491. this._vertexBuffers[kind].dispose();
  39492. }
  39493. this._vertexBuffers = {};
  39494. this._totalVertices = 0;
  39495. if (this._indexBuffer) {
  39496. this._engine._releaseBuffer(this._indexBuffer);
  39497. }
  39498. this._indexBuffer = null;
  39499. this._indices = [];
  39500. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39501. this.delayLoadingFile = null;
  39502. this._delayLoadingFunction = null;
  39503. this._delayInfo = [];
  39504. this._boundingInfo = null;
  39505. this._scene.removeGeometry(this);
  39506. this._isDisposed = true;
  39507. };
  39508. /**
  39509. * Clone the current geometry into a new geometry
  39510. * @param id defines the unique ID of the new geometry
  39511. * @returns a new geometry object
  39512. */
  39513. Geometry.prototype.copy = function (id) {
  39514. var vertexData = new BABYLON.VertexData();
  39515. vertexData.indices = [];
  39516. var indices = this.getIndices();
  39517. if (indices) {
  39518. for (var index = 0; index < indices.length; index++) {
  39519. vertexData.indices.push(indices[index]);
  39520. }
  39521. }
  39522. var updatable = false;
  39523. var stopChecking = false;
  39524. var kind;
  39525. for (kind in this._vertexBuffers) {
  39526. // using slice() to make a copy of the array and not just reference it
  39527. var data = this.getVerticesData(kind);
  39528. if (data instanceof Float32Array) {
  39529. vertexData.set(new Float32Array(data), kind);
  39530. }
  39531. else {
  39532. vertexData.set(data.slice(0), kind);
  39533. }
  39534. if (!stopChecking) {
  39535. var vb = this.getVertexBuffer(kind);
  39536. if (vb) {
  39537. updatable = vb.isUpdatable();
  39538. stopChecking = !updatable;
  39539. }
  39540. }
  39541. }
  39542. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39543. geometry.delayLoadState = this.delayLoadState;
  39544. geometry.delayLoadingFile = this.delayLoadingFile;
  39545. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39546. for (kind in this._delayInfo) {
  39547. geometry._delayInfo = geometry._delayInfo || [];
  39548. geometry._delayInfo.push(kind);
  39549. }
  39550. // Bounding info
  39551. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39552. return geometry;
  39553. };
  39554. /**
  39555. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39556. * @return a JSON representation of the current geometry data (without the vertices data)
  39557. */
  39558. Geometry.prototype.serialize = function () {
  39559. var serializationObject = {};
  39560. serializationObject.id = this.id;
  39561. serializationObject.updatable = this._updatable;
  39562. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39563. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39564. }
  39565. return serializationObject;
  39566. };
  39567. Geometry.prototype.toNumberArray = function (origin) {
  39568. if (Array.isArray(origin)) {
  39569. return origin;
  39570. }
  39571. else {
  39572. return Array.prototype.slice.call(origin);
  39573. }
  39574. };
  39575. /**
  39576. * Serialize all vertices data into a JSON oject
  39577. * @returns a JSON representation of the current geometry data
  39578. */
  39579. Geometry.prototype.serializeVerticeData = function () {
  39580. var serializationObject = this.serialize();
  39581. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39582. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39583. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39584. serializationObject.positions._updatable = true;
  39585. }
  39586. }
  39587. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39588. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39589. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39590. serializationObject.normals._updatable = true;
  39591. }
  39592. }
  39593. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39594. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39595. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39596. serializationObject.tangets._updatable = true;
  39597. }
  39598. }
  39599. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39600. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39601. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39602. serializationObject.uvs._updatable = true;
  39603. }
  39604. }
  39605. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39606. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39607. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39608. serializationObject.uv2s._updatable = true;
  39609. }
  39610. }
  39611. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39612. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39613. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39614. serializationObject.uv3s._updatable = true;
  39615. }
  39616. }
  39617. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39618. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39619. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39620. serializationObject.uv4s._updatable = true;
  39621. }
  39622. }
  39623. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39624. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39625. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39626. serializationObject.uv5s._updatable = true;
  39627. }
  39628. }
  39629. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39630. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39631. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39632. serializationObject.uv6s._updatable = true;
  39633. }
  39634. }
  39635. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39636. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39637. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39638. serializationObject.colors._updatable = true;
  39639. }
  39640. }
  39641. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39642. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39643. serializationObject.matricesIndices._isExpanded = true;
  39644. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39645. serializationObject.matricesIndices._updatable = true;
  39646. }
  39647. }
  39648. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39649. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39650. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39651. serializationObject.matricesWeights._updatable = true;
  39652. }
  39653. }
  39654. serializationObject.indices = this.toNumberArray(this.getIndices());
  39655. return serializationObject;
  39656. };
  39657. // Statics
  39658. /**
  39659. * Extracts a clone of a mesh geometry
  39660. * @param mesh defines the source mesh
  39661. * @param id defines the unique ID of the new geometry object
  39662. * @returns the new geometry object
  39663. */
  39664. Geometry.ExtractFromMesh = function (mesh, id) {
  39665. var geometry = mesh._geometry;
  39666. if (!geometry) {
  39667. return null;
  39668. }
  39669. return geometry.copy(id);
  39670. };
  39671. /**
  39672. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39673. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39674. * Be aware Math.random() could cause collisions, but:
  39675. * "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"
  39676. * @returns a string containing a new GUID
  39677. */
  39678. Geometry.RandomId = function () {
  39679. return BABYLON.Tools.RandomId();
  39680. };
  39681. /** @hidden */
  39682. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39683. var scene = mesh.getScene();
  39684. // Geometry
  39685. var geometryId = parsedGeometry.geometryId;
  39686. if (geometryId) {
  39687. var geometry = scene.getGeometryByID(geometryId);
  39688. if (geometry) {
  39689. geometry.applyToMesh(mesh);
  39690. }
  39691. }
  39692. else if (parsedGeometry instanceof ArrayBuffer) {
  39693. var binaryInfo = mesh._binaryInfo;
  39694. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39695. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39696. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39697. }
  39698. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39699. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39700. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39701. }
  39702. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39703. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39704. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39705. }
  39706. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39707. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39708. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39709. }
  39710. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39711. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39712. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39713. }
  39714. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39715. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39716. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39717. }
  39718. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39719. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39720. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39721. }
  39722. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39723. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39724. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39725. }
  39726. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39727. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39728. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39729. }
  39730. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39731. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39732. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39733. }
  39734. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39735. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39736. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39737. }
  39738. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39739. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39740. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39741. }
  39742. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39743. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39744. mesh.setIndices(indicesData, null);
  39745. }
  39746. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39747. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39748. mesh.subMeshes = [];
  39749. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39750. var materialIndex = subMeshesData[(i * 5) + 0];
  39751. var verticesStart = subMeshesData[(i * 5) + 1];
  39752. var verticesCount = subMeshesData[(i * 5) + 2];
  39753. var indexStart = subMeshesData[(i * 5) + 3];
  39754. var indexCount = subMeshesData[(i * 5) + 4];
  39755. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39756. }
  39757. }
  39758. }
  39759. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39760. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39761. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39762. if (parsedGeometry.tangents) {
  39763. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39764. }
  39765. if (parsedGeometry.uvs) {
  39766. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39767. }
  39768. if (parsedGeometry.uvs2) {
  39769. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39770. }
  39771. if (parsedGeometry.uvs3) {
  39772. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39773. }
  39774. if (parsedGeometry.uvs4) {
  39775. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39776. }
  39777. if (parsedGeometry.uvs5) {
  39778. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39779. }
  39780. if (parsedGeometry.uvs6) {
  39781. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39782. }
  39783. if (parsedGeometry.colors) {
  39784. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39785. }
  39786. if (parsedGeometry.matricesIndices) {
  39787. if (!parsedGeometry.matricesIndices._isExpanded) {
  39788. var floatIndices = [];
  39789. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39790. var matricesIndex = parsedGeometry.matricesIndices[i];
  39791. floatIndices.push(matricesIndex & 0x000000FF);
  39792. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39793. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39794. floatIndices.push(matricesIndex >> 24);
  39795. }
  39796. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39797. }
  39798. else {
  39799. delete parsedGeometry.matricesIndices._isExpanded;
  39800. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39801. }
  39802. }
  39803. if (parsedGeometry.matricesIndicesExtra) {
  39804. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39805. var floatIndices = [];
  39806. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39807. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39808. floatIndices.push(matricesIndex & 0x000000FF);
  39809. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39810. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39811. floatIndices.push(matricesIndex >> 24);
  39812. }
  39813. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39814. }
  39815. else {
  39816. delete parsedGeometry.matricesIndices._isExpanded;
  39817. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39818. }
  39819. }
  39820. if (parsedGeometry.matricesWeights) {
  39821. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39822. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39823. }
  39824. if (parsedGeometry.matricesWeightsExtra) {
  39825. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39826. }
  39827. mesh.setIndices(parsedGeometry.indices, null);
  39828. }
  39829. // SubMeshes
  39830. if (parsedGeometry.subMeshes) {
  39831. mesh.subMeshes = [];
  39832. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39833. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39834. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39835. }
  39836. }
  39837. // Flat shading
  39838. if (mesh._shouldGenerateFlatShading) {
  39839. mesh.convertToFlatShadedMesh();
  39840. delete mesh._shouldGenerateFlatShading;
  39841. }
  39842. // Update
  39843. mesh.computeWorldMatrix(true);
  39844. // Octree
  39845. var sceneOctree = scene.selectionOctree;
  39846. if (sceneOctree !== undefined && sceneOctree !== null) {
  39847. sceneOctree.addMesh(mesh);
  39848. }
  39849. };
  39850. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39851. var epsilon = 1e-3;
  39852. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39853. return;
  39854. }
  39855. var noInfluenceBoneIndex = 0.0;
  39856. if (parsedGeometry.skeletonId > -1) {
  39857. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39858. if (!skeleton) {
  39859. return;
  39860. }
  39861. noInfluenceBoneIndex = skeleton.bones.length;
  39862. }
  39863. else {
  39864. return;
  39865. }
  39866. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39867. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39868. var matricesWeights = parsedGeometry.matricesWeights;
  39869. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39870. var influencers = parsedGeometry.numBoneInfluencer;
  39871. var size = matricesWeights.length;
  39872. for (var i = 0; i < size; i += 4) {
  39873. var weight = 0.0;
  39874. var firstZeroWeight = -1;
  39875. for (var j = 0; j < 4; j++) {
  39876. var w = matricesWeights[i + j];
  39877. weight += w;
  39878. if (w < epsilon && firstZeroWeight < 0) {
  39879. firstZeroWeight = j;
  39880. }
  39881. }
  39882. if (matricesWeightsExtra) {
  39883. for (var j = 0; j < 4; j++) {
  39884. var w = matricesWeightsExtra[i + j];
  39885. weight += w;
  39886. if (w < epsilon && firstZeroWeight < 0) {
  39887. firstZeroWeight = j + 4;
  39888. }
  39889. }
  39890. }
  39891. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39892. firstZeroWeight = influencers - 1;
  39893. }
  39894. if (weight > epsilon) {
  39895. var mweight = 1.0 / weight;
  39896. for (var j = 0; j < 4; j++) {
  39897. matricesWeights[i + j] *= mweight;
  39898. }
  39899. if (matricesWeightsExtra) {
  39900. for (var j = 0; j < 4; j++) {
  39901. matricesWeightsExtra[i + j] *= mweight;
  39902. }
  39903. }
  39904. }
  39905. else {
  39906. if (firstZeroWeight >= 4) {
  39907. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39908. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39909. }
  39910. else {
  39911. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39912. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39913. }
  39914. }
  39915. }
  39916. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39917. if (parsedGeometry.matricesWeightsExtra) {
  39918. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39919. }
  39920. };
  39921. /**
  39922. * Create a new geometry from persisted data (Using .babylon file format)
  39923. * @param parsedVertexData defines the persisted data
  39924. * @param scene defines the hosting scene
  39925. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39926. * @returns the new geometry object
  39927. */
  39928. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39929. if (scene.getGeometryByID(parsedVertexData.id)) {
  39930. return null; // null since geometry could be something else than a box...
  39931. }
  39932. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39933. if (BABYLON.Tags) {
  39934. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39935. }
  39936. if (parsedVertexData.delayLoadingFile) {
  39937. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39938. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39939. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39940. geometry._delayInfo = [];
  39941. if (parsedVertexData.hasUVs) {
  39942. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39943. }
  39944. if (parsedVertexData.hasUVs2) {
  39945. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39946. }
  39947. if (parsedVertexData.hasUVs3) {
  39948. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39949. }
  39950. if (parsedVertexData.hasUVs4) {
  39951. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39952. }
  39953. if (parsedVertexData.hasUVs5) {
  39954. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39955. }
  39956. if (parsedVertexData.hasUVs6) {
  39957. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39958. }
  39959. if (parsedVertexData.hasColors) {
  39960. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39961. }
  39962. if (parsedVertexData.hasMatricesIndices) {
  39963. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39964. }
  39965. if (parsedVertexData.hasMatricesWeights) {
  39966. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39967. }
  39968. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39969. }
  39970. else {
  39971. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39972. }
  39973. scene.pushGeometry(geometry, true);
  39974. return geometry;
  39975. };
  39976. return Geometry;
  39977. }());
  39978. BABYLON.Geometry = Geometry;
  39979. // Primitives
  39980. /// Abstract class
  39981. /**
  39982. * Abstract class used to provide common services for all typed geometries
  39983. * @hidden
  39984. */
  39985. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39986. __extends(_PrimitiveGeometry, _super);
  39987. /**
  39988. * Creates a new typed geometry
  39989. * @param id defines the unique ID of the geometry
  39990. * @param scene defines the hosting scene
  39991. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39992. * @param mesh defines the hosting mesh (can be null)
  39993. */
  39994. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39995. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39996. if (mesh === void 0) { mesh = null; }
  39997. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39998. _this._canBeRegenerated = _canBeRegenerated;
  39999. _this._beingRegenerated = true;
  40000. _this.regenerate();
  40001. _this._beingRegenerated = false;
  40002. return _this;
  40003. }
  40004. /**
  40005. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40006. * @returns true if the geometry can be regenerated
  40007. */
  40008. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40009. return this._canBeRegenerated;
  40010. };
  40011. /**
  40012. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40013. */
  40014. _PrimitiveGeometry.prototype.regenerate = function () {
  40015. if (!this._canBeRegenerated) {
  40016. return;
  40017. }
  40018. this._beingRegenerated = true;
  40019. this.setAllVerticesData(this._regenerateVertexData(), false);
  40020. this._beingRegenerated = false;
  40021. };
  40022. /**
  40023. * Clone the geometry
  40024. * @param id defines the unique ID of the new geometry
  40025. * @returns the new geometry
  40026. */
  40027. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40028. return _super.prototype.copy.call(this, id);
  40029. };
  40030. // overrides
  40031. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40032. if (!this._beingRegenerated) {
  40033. return;
  40034. }
  40035. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40036. };
  40037. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40038. if (!this._beingRegenerated) {
  40039. return;
  40040. }
  40041. _super.prototype.setVerticesData.call(this, kind, data, false);
  40042. };
  40043. // to override
  40044. /** @hidden */
  40045. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40046. throw new Error("Abstract method");
  40047. };
  40048. _PrimitiveGeometry.prototype.copy = function (id) {
  40049. throw new Error("Must be overriden in sub-classes.");
  40050. };
  40051. _PrimitiveGeometry.prototype.serialize = function () {
  40052. var serializationObject = _super.prototype.serialize.call(this);
  40053. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40054. return serializationObject;
  40055. };
  40056. return _PrimitiveGeometry;
  40057. }(Geometry));
  40058. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40059. /**
  40060. * Creates a ribbon geometry
  40061. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40062. */
  40063. var RibbonGeometry = /** @class */ (function (_super) {
  40064. __extends(RibbonGeometry, _super);
  40065. /**
  40066. * Creates a ribbon geometry
  40067. * @param id defines the unique ID of the geometry
  40068. * @param scene defines the hosting scene
  40069. * @param pathArray defines the array of paths to use
  40070. * @param closeArray defines if the last path and the first path must be joined
  40071. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40072. * @param offset defines the offset between points
  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 RibbonGeometry(id, scene,
  40078. /**
  40079. * Defines the array of paths to use
  40080. */
  40081. pathArray,
  40082. /**
  40083. * Defines if the last and first points of each path in your pathArray must be joined
  40084. */
  40085. closeArray,
  40086. /**
  40087. * Defines if the last and first points of each path in your pathArray must be joined
  40088. */
  40089. closePath,
  40090. /**
  40091. * Defines the offset between points
  40092. */
  40093. offset, canBeRegenerated, mesh,
  40094. /**
  40095. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40096. */
  40097. side) {
  40098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40099. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40100. _this.pathArray = pathArray;
  40101. _this.closeArray = closeArray;
  40102. _this.closePath = closePath;
  40103. _this.offset = offset;
  40104. _this.side = side;
  40105. return _this;
  40106. }
  40107. /** @hidden */
  40108. RibbonGeometry.prototype._regenerateVertexData = function () {
  40109. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40110. };
  40111. RibbonGeometry.prototype.copy = function (id) {
  40112. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40113. };
  40114. return RibbonGeometry;
  40115. }(_PrimitiveGeometry));
  40116. BABYLON.RibbonGeometry = RibbonGeometry;
  40117. /**
  40118. * Creates a box geometry
  40119. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40120. */
  40121. var BoxGeometry = /** @class */ (function (_super) {
  40122. __extends(BoxGeometry, _super);
  40123. /**
  40124. * Creates a box geometry
  40125. * @param id defines the unique ID of the geometry
  40126. * @param scene defines the hosting scene
  40127. * @param size defines the zise of the box (width, height and depth are the same)
  40128. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40129. * @param mesh defines the hosting mesh (can be null)
  40130. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40131. */
  40132. function BoxGeometry(id, scene,
  40133. /**
  40134. * Defines the zise of the box (width, height and depth are the same)
  40135. */
  40136. size, canBeRegenerated, mesh,
  40137. /**
  40138. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40139. */
  40140. side) {
  40141. if (mesh === void 0) { mesh = null; }
  40142. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40143. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40144. _this.size = size;
  40145. _this.side = side;
  40146. return _this;
  40147. }
  40148. BoxGeometry.prototype._regenerateVertexData = function () {
  40149. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40150. };
  40151. BoxGeometry.prototype.copy = function (id) {
  40152. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40153. };
  40154. BoxGeometry.prototype.serialize = function () {
  40155. var serializationObject = _super.prototype.serialize.call(this);
  40156. serializationObject.size = this.size;
  40157. return serializationObject;
  40158. };
  40159. BoxGeometry.Parse = function (parsedBox, scene) {
  40160. if (scene.getGeometryByID(parsedBox.id)) {
  40161. return null; // null since geometry could be something else than a box...
  40162. }
  40163. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40164. if (BABYLON.Tags) {
  40165. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40166. }
  40167. scene.pushGeometry(box, true);
  40168. return box;
  40169. };
  40170. return BoxGeometry;
  40171. }(_PrimitiveGeometry));
  40172. BABYLON.BoxGeometry = BoxGeometry;
  40173. /**
  40174. * Creates a sphere geometry
  40175. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40176. */
  40177. var SphereGeometry = /** @class */ (function (_super) {
  40178. __extends(SphereGeometry, _super);
  40179. /**
  40180. * Create a new sphere geometry
  40181. * @param id defines the unique ID of the geometry
  40182. * @param scene defines the hosting scene
  40183. * @param segments defines the number of segments to use to create the sphere
  40184. * @param diameter defines the diameter of the sphere
  40185. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40186. * @param mesh defines the hosting mesh (can be null)
  40187. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40188. */
  40189. function SphereGeometry(id, scene,
  40190. /**
  40191. * Defines the number of segments to use to create the sphere
  40192. */
  40193. segments,
  40194. /**
  40195. * Defines the diameter of the sphere
  40196. */
  40197. diameter, canBeRegenerated, mesh,
  40198. /**
  40199. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40200. */
  40201. side) {
  40202. if (mesh === void 0) { mesh = null; }
  40203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40204. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40205. _this.segments = segments;
  40206. _this.diameter = diameter;
  40207. _this.side = side;
  40208. return _this;
  40209. }
  40210. SphereGeometry.prototype._regenerateVertexData = function () {
  40211. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40212. };
  40213. SphereGeometry.prototype.copy = function (id) {
  40214. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40215. };
  40216. SphereGeometry.prototype.serialize = function () {
  40217. var serializationObject = _super.prototype.serialize.call(this);
  40218. serializationObject.segments = this.segments;
  40219. serializationObject.diameter = this.diameter;
  40220. return serializationObject;
  40221. };
  40222. SphereGeometry.Parse = function (parsedSphere, scene) {
  40223. if (scene.getGeometryByID(parsedSphere.id)) {
  40224. return null; // null since geometry could be something else than a sphere...
  40225. }
  40226. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40227. if (BABYLON.Tags) {
  40228. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40229. }
  40230. scene.pushGeometry(sphere, true);
  40231. return sphere;
  40232. };
  40233. return SphereGeometry;
  40234. }(_PrimitiveGeometry));
  40235. BABYLON.SphereGeometry = SphereGeometry;
  40236. /**
  40237. * Creates a disc geometry
  40238. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40239. */
  40240. var DiscGeometry = /** @class */ (function (_super) {
  40241. __extends(DiscGeometry, _super);
  40242. /**
  40243. * Creates a new disc geometry
  40244. * @param id defines the unique ID of the geometry
  40245. * @param scene defines the hosting scene
  40246. * @param radius defines the radius of the disc
  40247. * @param tessellation defines the tesselation factor to apply to the disc
  40248. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40249. * @param mesh defines the hosting mesh (can be null)
  40250. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40251. */
  40252. function DiscGeometry(id, scene,
  40253. /**
  40254. * Defines the radius of the disc
  40255. */
  40256. radius,
  40257. /**
  40258. * Defines the tesselation factor to apply to the disc
  40259. */
  40260. tessellation, canBeRegenerated, mesh,
  40261. /**
  40262. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40263. */
  40264. side) {
  40265. if (mesh === void 0) { mesh = null; }
  40266. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40267. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40268. _this.radius = radius;
  40269. _this.tessellation = tessellation;
  40270. _this.side = side;
  40271. return _this;
  40272. }
  40273. DiscGeometry.prototype._regenerateVertexData = function () {
  40274. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40275. };
  40276. DiscGeometry.prototype.copy = function (id) {
  40277. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40278. };
  40279. return DiscGeometry;
  40280. }(_PrimitiveGeometry));
  40281. BABYLON.DiscGeometry = DiscGeometry;
  40282. /**
  40283. * Creates a new cylinder geometry
  40284. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40285. */
  40286. var CylinderGeometry = /** @class */ (function (_super) {
  40287. __extends(CylinderGeometry, _super);
  40288. /**
  40289. * Creates a new cylinder geometry
  40290. * @param id defines the unique ID of the geometry
  40291. * @param scene defines the hosting scene
  40292. * @param height defines the height of the cylinder
  40293. * @param diameterTop defines the diameter of the cylinder's top cap
  40294. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40295. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40296. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40297. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40298. * @param mesh defines the hosting mesh (can be null)
  40299. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40300. */
  40301. function CylinderGeometry(id, scene,
  40302. /**
  40303. * Defines the height of the cylinder
  40304. */
  40305. height,
  40306. /**
  40307. * Defines the diameter of the cylinder's top cap
  40308. */
  40309. diameterTop,
  40310. /**
  40311. * Defines the diameter of the cylinder's bottom cap
  40312. */
  40313. diameterBottom,
  40314. /**
  40315. * Defines the tessellation factor to apply to the cylinder
  40316. */
  40317. tessellation,
  40318. /**
  40319. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40320. */
  40321. subdivisions, canBeRegenerated, mesh,
  40322. /**
  40323. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40324. */
  40325. side) {
  40326. if (subdivisions === void 0) { subdivisions = 1; }
  40327. if (mesh === void 0) { mesh = null; }
  40328. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40329. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40330. _this.height = height;
  40331. _this.diameterTop = diameterTop;
  40332. _this.diameterBottom = diameterBottom;
  40333. _this.tessellation = tessellation;
  40334. _this.subdivisions = subdivisions;
  40335. _this.side = side;
  40336. return _this;
  40337. }
  40338. CylinderGeometry.prototype._regenerateVertexData = function () {
  40339. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40340. };
  40341. CylinderGeometry.prototype.copy = function (id) {
  40342. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40343. };
  40344. CylinderGeometry.prototype.serialize = function () {
  40345. var serializationObject = _super.prototype.serialize.call(this);
  40346. serializationObject.height = this.height;
  40347. serializationObject.diameterTop = this.diameterTop;
  40348. serializationObject.diameterBottom = this.diameterBottom;
  40349. serializationObject.tessellation = this.tessellation;
  40350. return serializationObject;
  40351. };
  40352. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40353. if (scene.getGeometryByID(parsedCylinder.id)) {
  40354. return null; // null since geometry could be something else than a cylinder...
  40355. }
  40356. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40357. if (BABYLON.Tags) {
  40358. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40359. }
  40360. scene.pushGeometry(cylinder, true);
  40361. return cylinder;
  40362. };
  40363. return CylinderGeometry;
  40364. }(_PrimitiveGeometry));
  40365. BABYLON.CylinderGeometry = CylinderGeometry;
  40366. /**
  40367. * Creates a new torus geometry
  40368. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40369. */
  40370. var TorusGeometry = /** @class */ (function (_super) {
  40371. __extends(TorusGeometry, _super);
  40372. /**
  40373. * Creates a new torus geometry
  40374. * @param id defines the unique ID of the geometry
  40375. * @param scene defines the hosting scene
  40376. * @param diameter defines the diameter of the torus
  40377. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40378. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40379. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40380. * @param mesh defines the hosting mesh (can be null)
  40381. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40382. */
  40383. function TorusGeometry(id, scene,
  40384. /**
  40385. * Defines the diameter of the torus
  40386. */
  40387. diameter,
  40388. /**
  40389. * Defines the thickness of the torus (ie. internal diameter)
  40390. */
  40391. thickness,
  40392. /**
  40393. * Defines the tesselation factor to apply to the torus
  40394. */
  40395. tessellation, canBeRegenerated, mesh,
  40396. /**
  40397. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40398. */
  40399. side) {
  40400. if (mesh === void 0) { mesh = null; }
  40401. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40402. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40403. _this.diameter = diameter;
  40404. _this.thickness = thickness;
  40405. _this.tessellation = tessellation;
  40406. _this.side = side;
  40407. return _this;
  40408. }
  40409. TorusGeometry.prototype._regenerateVertexData = function () {
  40410. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40411. };
  40412. TorusGeometry.prototype.copy = function (id) {
  40413. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40414. };
  40415. TorusGeometry.prototype.serialize = function () {
  40416. var serializationObject = _super.prototype.serialize.call(this);
  40417. serializationObject.diameter = this.diameter;
  40418. serializationObject.thickness = this.thickness;
  40419. serializationObject.tessellation = this.tessellation;
  40420. return serializationObject;
  40421. };
  40422. TorusGeometry.Parse = function (parsedTorus, scene) {
  40423. if (scene.getGeometryByID(parsedTorus.id)) {
  40424. return null; // null since geometry could be something else than a torus...
  40425. }
  40426. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40427. if (BABYLON.Tags) {
  40428. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40429. }
  40430. scene.pushGeometry(torus, true);
  40431. return torus;
  40432. };
  40433. return TorusGeometry;
  40434. }(_PrimitiveGeometry));
  40435. BABYLON.TorusGeometry = TorusGeometry;
  40436. /**
  40437. * Creates a new ground geometry
  40438. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40439. */
  40440. var GroundGeometry = /** @class */ (function (_super) {
  40441. __extends(GroundGeometry, _super);
  40442. /**
  40443. * Creates a new ground geometry
  40444. * @param id defines the unique ID of the geometry
  40445. * @param scene defines the hosting scene
  40446. * @param width defines the width of the ground
  40447. * @param height defines the height of the ground
  40448. * @param subdivisions defines the subdivisions to apply to the ground
  40449. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40450. * @param mesh defines the hosting mesh (can be null)
  40451. */
  40452. function GroundGeometry(id, scene,
  40453. /**
  40454. * Defines the width of the ground
  40455. */
  40456. width,
  40457. /**
  40458. * Defines the height of the ground
  40459. */
  40460. height,
  40461. /**
  40462. * Defines the subdivisions to apply to the ground
  40463. */
  40464. subdivisions, canBeRegenerated, mesh) {
  40465. if (mesh === void 0) { mesh = null; }
  40466. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40467. _this.width = width;
  40468. _this.height = height;
  40469. _this.subdivisions = subdivisions;
  40470. return _this;
  40471. }
  40472. GroundGeometry.prototype._regenerateVertexData = function () {
  40473. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40474. };
  40475. GroundGeometry.prototype.copy = function (id) {
  40476. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40477. };
  40478. GroundGeometry.prototype.serialize = function () {
  40479. var serializationObject = _super.prototype.serialize.call(this);
  40480. serializationObject.width = this.width;
  40481. serializationObject.height = this.height;
  40482. serializationObject.subdivisions = this.subdivisions;
  40483. return serializationObject;
  40484. };
  40485. GroundGeometry.Parse = function (parsedGround, scene) {
  40486. if (scene.getGeometryByID(parsedGround.id)) {
  40487. return null; // null since geometry could be something else than a ground...
  40488. }
  40489. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40490. if (BABYLON.Tags) {
  40491. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40492. }
  40493. scene.pushGeometry(ground, true);
  40494. return ground;
  40495. };
  40496. return GroundGeometry;
  40497. }(_PrimitiveGeometry));
  40498. BABYLON.GroundGeometry = GroundGeometry;
  40499. /**
  40500. * Creates a tiled ground geometry
  40501. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40502. */
  40503. var TiledGroundGeometry = /** @class */ (function (_super) {
  40504. __extends(TiledGroundGeometry, _super);
  40505. /**
  40506. * Creates a tiled ground geometry
  40507. * @param id defines the unique ID of the geometry
  40508. * @param scene defines the hosting scene
  40509. * @param xmin defines the minimum value on X axis
  40510. * @param zmin defines the minimum value on Z axis
  40511. * @param xmax defines the maximum value on X axis
  40512. * @param zmax defines the maximum value on Z axis
  40513. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40514. * @param precision defines the precision to use when computing the tiles
  40515. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40516. * @param mesh defines the hosting mesh (can be null)
  40517. */
  40518. function TiledGroundGeometry(id, scene,
  40519. /**
  40520. * Defines the minimum value on X axis
  40521. */
  40522. xmin,
  40523. /**
  40524. * Defines the minimum value on Z axis
  40525. */
  40526. zmin,
  40527. /**
  40528. * Defines the maximum value on X axis
  40529. */
  40530. xmax,
  40531. /**
  40532. * Defines the maximum value on Z axis
  40533. */
  40534. zmax,
  40535. /**
  40536. * Defines the subdivisions to apply to the ground
  40537. */
  40538. subdivisions,
  40539. /**
  40540. * Defines the precision to use when computing the tiles
  40541. */
  40542. precision, canBeRegenerated, mesh) {
  40543. if (mesh === void 0) { mesh = null; }
  40544. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40545. _this.xmin = xmin;
  40546. _this.zmin = zmin;
  40547. _this.xmax = xmax;
  40548. _this.zmax = zmax;
  40549. _this.subdivisions = subdivisions;
  40550. _this.precision = precision;
  40551. return _this;
  40552. }
  40553. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40554. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40555. };
  40556. TiledGroundGeometry.prototype.copy = function (id) {
  40557. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40558. };
  40559. return TiledGroundGeometry;
  40560. }(_PrimitiveGeometry));
  40561. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40562. /**
  40563. * Creates a plane geometry
  40564. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40565. */
  40566. var PlaneGeometry = /** @class */ (function (_super) {
  40567. __extends(PlaneGeometry, _super);
  40568. /**
  40569. * Creates a plane geometry
  40570. * @param id defines the unique ID of the geometry
  40571. * @param scene defines the hosting scene
  40572. * @param size defines the size of the plane (width === height)
  40573. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40574. * @param mesh defines the hosting mesh (can be null)
  40575. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40576. */
  40577. function PlaneGeometry(id, scene,
  40578. /**
  40579. * Defines the size of the plane (width === height)
  40580. */
  40581. size, canBeRegenerated, mesh,
  40582. /**
  40583. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40584. */
  40585. side) {
  40586. if (mesh === void 0) { mesh = null; }
  40587. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40588. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40589. _this.size = size;
  40590. _this.side = side;
  40591. return _this;
  40592. }
  40593. PlaneGeometry.prototype._regenerateVertexData = function () {
  40594. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40595. };
  40596. PlaneGeometry.prototype.copy = function (id) {
  40597. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40598. };
  40599. PlaneGeometry.prototype.serialize = function () {
  40600. var serializationObject = _super.prototype.serialize.call(this);
  40601. serializationObject.size = this.size;
  40602. return serializationObject;
  40603. };
  40604. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40605. if (scene.getGeometryByID(parsedPlane.id)) {
  40606. return null; // null since geometry could be something else than a ground...
  40607. }
  40608. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40609. if (BABYLON.Tags) {
  40610. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40611. }
  40612. scene.pushGeometry(plane, true);
  40613. return plane;
  40614. };
  40615. return PlaneGeometry;
  40616. }(_PrimitiveGeometry));
  40617. BABYLON.PlaneGeometry = PlaneGeometry;
  40618. /**
  40619. * Creates a torus knot geometry
  40620. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40621. */
  40622. var TorusKnotGeometry = /** @class */ (function (_super) {
  40623. __extends(TorusKnotGeometry, _super);
  40624. /**
  40625. * Creates a torus knot geometry
  40626. * @param id defines the unique ID of the geometry
  40627. * @param scene defines the hosting scene
  40628. * @param radius defines the radius of the torus knot
  40629. * @param tube defines the thickness of the torus knot tube
  40630. * @param radialSegments defines the number of radial segments
  40631. * @param tubularSegments defines the number of tubular segments
  40632. * @param p defines the first number of windings
  40633. * @param q defines the second number of windings
  40634. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40635. * @param mesh defines the hosting mesh (can be null)
  40636. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40637. */
  40638. function TorusKnotGeometry(id, scene,
  40639. /**
  40640. * Defines the radius of the torus knot
  40641. */
  40642. radius,
  40643. /**
  40644. * Defines the thickness of the torus knot tube
  40645. */
  40646. tube,
  40647. /**
  40648. * Defines the number of radial segments
  40649. */
  40650. radialSegments,
  40651. /**
  40652. * Defines the number of tubular segments
  40653. */
  40654. tubularSegments,
  40655. /**
  40656. * Defines the first number of windings
  40657. */
  40658. p,
  40659. /**
  40660. * Defines the second number of windings
  40661. */
  40662. q, canBeRegenerated, mesh,
  40663. /**
  40664. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40665. */
  40666. side) {
  40667. if (mesh === void 0) { mesh = null; }
  40668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40669. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40670. _this.radius = radius;
  40671. _this.tube = tube;
  40672. _this.radialSegments = radialSegments;
  40673. _this.tubularSegments = tubularSegments;
  40674. _this.p = p;
  40675. _this.q = q;
  40676. _this.side = side;
  40677. return _this;
  40678. }
  40679. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40680. 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 });
  40681. };
  40682. TorusKnotGeometry.prototype.copy = function (id) {
  40683. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40684. };
  40685. TorusKnotGeometry.prototype.serialize = function () {
  40686. var serializationObject = _super.prototype.serialize.call(this);
  40687. serializationObject.radius = this.radius;
  40688. serializationObject.tube = this.tube;
  40689. serializationObject.radialSegments = this.radialSegments;
  40690. serializationObject.tubularSegments = this.tubularSegments;
  40691. serializationObject.p = this.p;
  40692. serializationObject.q = this.q;
  40693. return serializationObject;
  40694. };
  40695. ;
  40696. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40697. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40698. return null; // null since geometry could be something else than a ground...
  40699. }
  40700. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40701. if (BABYLON.Tags) {
  40702. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40703. }
  40704. scene.pushGeometry(torusKnot, true);
  40705. return torusKnot;
  40706. };
  40707. return TorusKnotGeometry;
  40708. }(_PrimitiveGeometry));
  40709. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40710. //}
  40711. })(BABYLON || (BABYLON = {}));
  40712. //# sourceMappingURL=babylon.geometry.js.map
  40713. var BABYLON;
  40714. (function (BABYLON) {
  40715. /**
  40716. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40717. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40718. */
  40719. var PostProcessManager = /** @class */ (function () {
  40720. /**
  40721. * Creates a new instance PostProcess
  40722. * @param scene The scene that the post process is associated with.
  40723. */
  40724. function PostProcessManager(scene) {
  40725. this._vertexBuffers = {};
  40726. this._scene = scene;
  40727. }
  40728. PostProcessManager.prototype._prepareBuffers = function () {
  40729. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40730. return;
  40731. }
  40732. // VBO
  40733. var vertices = [];
  40734. vertices.push(1, 1);
  40735. vertices.push(-1, 1);
  40736. vertices.push(-1, -1);
  40737. vertices.push(1, -1);
  40738. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40739. this._buildIndexBuffer();
  40740. };
  40741. PostProcessManager.prototype._buildIndexBuffer = function () {
  40742. // Indices
  40743. var indices = [];
  40744. indices.push(0);
  40745. indices.push(1);
  40746. indices.push(2);
  40747. indices.push(0);
  40748. indices.push(2);
  40749. indices.push(3);
  40750. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40751. };
  40752. /**
  40753. * Rebuilds the vertex buffers of the manager.
  40754. */
  40755. PostProcessManager.prototype._rebuild = function () {
  40756. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40757. if (!vb) {
  40758. return;
  40759. }
  40760. vb._rebuild();
  40761. this._buildIndexBuffer();
  40762. };
  40763. // Methods
  40764. /**
  40765. * Prepares a frame to be run through a post process.
  40766. * @param sourceTexture The input texture to the post procesess. (default: null)
  40767. * @param postProcesses An array of post processes to be run. (default: null)
  40768. * @returns True if the post processes were able to be run.
  40769. */
  40770. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40771. if (sourceTexture === void 0) { sourceTexture = null; }
  40772. if (postProcesses === void 0) { postProcesses = null; }
  40773. var camera = this._scene.activeCamera;
  40774. if (!camera) {
  40775. return false;
  40776. }
  40777. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40778. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40779. return false;
  40780. }
  40781. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40782. return true;
  40783. };
  40784. /**
  40785. * Manually render a set of post processes to a texture.
  40786. * @param postProcesses An array of post processes to be run.
  40787. * @param targetTexture The target texture to render to.
  40788. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40789. */
  40790. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40791. if (targetTexture === void 0) { targetTexture = null; }
  40792. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40793. var engine = this._scene.getEngine();
  40794. for (var index = 0; index < postProcesses.length; index++) {
  40795. if (index < postProcesses.length - 1) {
  40796. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40797. }
  40798. else {
  40799. if (targetTexture) {
  40800. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40801. }
  40802. else {
  40803. engine.restoreDefaultFramebuffer();
  40804. }
  40805. }
  40806. var pp = postProcesses[index];
  40807. var effect = pp.apply();
  40808. if (effect) {
  40809. pp.onBeforeRenderObservable.notifyObservers(effect);
  40810. // VBOs
  40811. this._prepareBuffers();
  40812. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40813. // Draw order
  40814. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40815. pp.onAfterRenderObservable.notifyObservers(effect);
  40816. }
  40817. }
  40818. // Restore depth buffer
  40819. engine.setDepthBuffer(true);
  40820. engine.setDepthWrite(true);
  40821. };
  40822. /**
  40823. * Finalize the result of the output of the postprocesses.
  40824. * @param doNotPresent If true the result will not be displayed to the screen.
  40825. * @param targetTexture The target texture to render to.
  40826. * @param faceIndex The index of the face to bind the target texture to.
  40827. * @param postProcesses The array of post processes to render.
  40828. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40829. */
  40830. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40831. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40832. var camera = this._scene.activeCamera;
  40833. if (!camera) {
  40834. return;
  40835. }
  40836. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40837. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40838. return;
  40839. }
  40840. var engine = this._scene.getEngine();
  40841. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40842. var pp = postProcesses[index];
  40843. if (index < len - 1) {
  40844. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40845. }
  40846. else {
  40847. if (targetTexture) {
  40848. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40849. pp._outputTexture = targetTexture;
  40850. }
  40851. else {
  40852. engine.restoreDefaultFramebuffer();
  40853. pp._outputTexture = null;
  40854. }
  40855. }
  40856. if (doNotPresent) {
  40857. break;
  40858. }
  40859. var effect = pp.apply();
  40860. if (effect) {
  40861. pp.onBeforeRenderObservable.notifyObservers(effect);
  40862. // VBOs
  40863. this._prepareBuffers();
  40864. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40865. // Draw order
  40866. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40867. pp.onAfterRenderObservable.notifyObservers(effect);
  40868. }
  40869. }
  40870. // Restore states
  40871. engine.setDepthBuffer(true);
  40872. engine.setDepthWrite(true);
  40873. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40874. };
  40875. /**
  40876. * Disposes of the post process manager.
  40877. */
  40878. PostProcessManager.prototype.dispose = function () {
  40879. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40880. if (buffer) {
  40881. buffer.dispose();
  40882. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40883. }
  40884. if (this._indexBuffer) {
  40885. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40886. this._indexBuffer = null;
  40887. }
  40888. };
  40889. return PostProcessManager;
  40890. }());
  40891. BABYLON.PostProcessManager = PostProcessManager;
  40892. })(BABYLON || (BABYLON = {}));
  40893. //# sourceMappingURL=babylon.postProcessManager.js.map
  40894. var BABYLON;
  40895. (function (BABYLON) {
  40896. /**
  40897. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40898. */
  40899. var PerformanceMonitor = /** @class */ (function () {
  40900. /**
  40901. * constructor
  40902. * @param frameSampleSize The number of samples required to saturate the sliding window
  40903. */
  40904. function PerformanceMonitor(frameSampleSize) {
  40905. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40906. this._enabled = true;
  40907. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40908. }
  40909. /**
  40910. * Samples current frame
  40911. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40912. */
  40913. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40914. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40915. if (!this._enabled)
  40916. return;
  40917. if (this._lastFrameTimeMs != null) {
  40918. var dt = timeMs - this._lastFrameTimeMs;
  40919. this._rollingFrameTime.add(dt);
  40920. }
  40921. this._lastFrameTimeMs = timeMs;
  40922. };
  40923. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40924. /**
  40925. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40926. * @return Average frame time in milliseconds
  40927. */
  40928. get: function () {
  40929. return this._rollingFrameTime.average;
  40930. },
  40931. enumerable: true,
  40932. configurable: true
  40933. });
  40934. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40935. /**
  40936. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40937. * @return Frame time variance in milliseconds squared
  40938. */
  40939. get: function () {
  40940. return this._rollingFrameTime.variance;
  40941. },
  40942. enumerable: true,
  40943. configurable: true
  40944. });
  40945. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40946. /**
  40947. * Returns the frame time of the most recent frame
  40948. * @return Frame time in milliseconds
  40949. */
  40950. get: function () {
  40951. return this._rollingFrameTime.history(0);
  40952. },
  40953. enumerable: true,
  40954. configurable: true
  40955. });
  40956. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40957. /**
  40958. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40959. * @return Framerate in frames per second
  40960. */
  40961. get: function () {
  40962. return 1000.0 / this._rollingFrameTime.average;
  40963. },
  40964. enumerable: true,
  40965. configurable: true
  40966. });
  40967. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40968. /**
  40969. * Returns the average framerate in frames per second using the most recent frame time
  40970. * @return Framerate in frames per second
  40971. */
  40972. get: function () {
  40973. var history = this._rollingFrameTime.history(0);
  40974. if (history === 0) {
  40975. return 0;
  40976. }
  40977. return 1000.0 / history;
  40978. },
  40979. enumerable: true,
  40980. configurable: true
  40981. });
  40982. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40983. /**
  40984. * Returns true if enough samples have been taken to completely fill the sliding window
  40985. * @return true if saturated
  40986. */
  40987. get: function () {
  40988. return this._rollingFrameTime.isSaturated();
  40989. },
  40990. enumerable: true,
  40991. configurable: true
  40992. });
  40993. /**
  40994. * Enables contributions to the sliding window sample set
  40995. */
  40996. PerformanceMonitor.prototype.enable = function () {
  40997. this._enabled = true;
  40998. };
  40999. /**
  41000. * Disables contributions to the sliding window sample set
  41001. * Samples will not be interpolated over the disabled period
  41002. */
  41003. PerformanceMonitor.prototype.disable = function () {
  41004. this._enabled = false;
  41005. //clear last sample to avoid interpolating over the disabled period when next enabled
  41006. this._lastFrameTimeMs = null;
  41007. };
  41008. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41009. /**
  41010. * Returns true if sampling is enabled
  41011. * @return true if enabled
  41012. */
  41013. get: function () {
  41014. return this._enabled;
  41015. },
  41016. enumerable: true,
  41017. configurable: true
  41018. });
  41019. /**
  41020. * Resets performance monitor
  41021. */
  41022. PerformanceMonitor.prototype.reset = function () {
  41023. //clear last sample to avoid interpolating over the disabled period when next enabled
  41024. this._lastFrameTimeMs = null;
  41025. //wipe record
  41026. this._rollingFrameTime.reset();
  41027. };
  41028. return PerformanceMonitor;
  41029. }());
  41030. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41031. /**
  41032. * RollingAverage
  41033. *
  41034. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41035. */
  41036. var RollingAverage = /** @class */ (function () {
  41037. /**
  41038. * constructor
  41039. * @param length The number of samples required to saturate the sliding window
  41040. */
  41041. function RollingAverage(length) {
  41042. this._samples = new Array(length);
  41043. this.reset();
  41044. }
  41045. /**
  41046. * Adds a sample to the sample set
  41047. * @param v The sample value
  41048. */
  41049. RollingAverage.prototype.add = function (v) {
  41050. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41051. var delta;
  41052. //we need to check if we've already wrapped round
  41053. if (this.isSaturated()) {
  41054. //remove bottom of stack from mean
  41055. var bottomValue = this._samples[this._pos];
  41056. delta = bottomValue - this.average;
  41057. this.average -= delta / (this._sampleCount - 1);
  41058. this._m2 -= delta * (bottomValue - this.average);
  41059. }
  41060. else {
  41061. this._sampleCount++;
  41062. }
  41063. //add new value to mean
  41064. delta = v - this.average;
  41065. this.average += delta / (this._sampleCount);
  41066. this._m2 += delta * (v - this.average);
  41067. //set the new variance
  41068. this.variance = this._m2 / (this._sampleCount - 1);
  41069. this._samples[this._pos] = v;
  41070. this._pos++;
  41071. this._pos %= this._samples.length; //positive wrap around
  41072. };
  41073. /**
  41074. * Returns previously added values or null if outside of history or outside the sliding window domain
  41075. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41076. * @return Value previously recorded with add() or null if outside of range
  41077. */
  41078. RollingAverage.prototype.history = function (i) {
  41079. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41080. return 0;
  41081. }
  41082. var i0 = this._wrapPosition(this._pos - 1.0);
  41083. return this._samples[this._wrapPosition(i0 - i)];
  41084. };
  41085. /**
  41086. * Returns true if enough samples have been taken to completely fill the sliding window
  41087. * @return true if sample-set saturated
  41088. */
  41089. RollingAverage.prototype.isSaturated = function () {
  41090. return this._sampleCount >= this._samples.length;
  41091. };
  41092. /**
  41093. * Resets the rolling average (equivalent to 0 samples taken so far)
  41094. */
  41095. RollingAverage.prototype.reset = function () {
  41096. this.average = 0;
  41097. this.variance = 0;
  41098. this._sampleCount = 0;
  41099. this._pos = 0;
  41100. this._m2 = 0;
  41101. };
  41102. /**
  41103. * Wraps a value around the sample range boundaries
  41104. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41105. * @return Wrapped position in sample range
  41106. */
  41107. RollingAverage.prototype._wrapPosition = function (i) {
  41108. var max = this._samples.length;
  41109. return ((i % max) + max) % max;
  41110. };
  41111. return RollingAverage;
  41112. }());
  41113. BABYLON.RollingAverage = RollingAverage;
  41114. })(BABYLON || (BABYLON = {}));
  41115. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41116. var BABYLON;
  41117. (function (BABYLON) {
  41118. /**
  41119. * This groups together the common properties used for image processing either in direct forward pass
  41120. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41121. * or not.
  41122. */
  41123. var ImageProcessingConfiguration = /** @class */ (function () {
  41124. function ImageProcessingConfiguration() {
  41125. /**
  41126. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41127. */
  41128. this.colorCurves = new BABYLON.ColorCurves();
  41129. this._colorCurvesEnabled = false;
  41130. this._colorGradingEnabled = false;
  41131. this._colorGradingWithGreenDepth = true;
  41132. this._colorGradingBGR = true;
  41133. this._exposure = 1.0;
  41134. this._toneMappingEnabled = false;
  41135. this._contrast = 1.0;
  41136. /**
  41137. * Vignette stretch size.
  41138. */
  41139. this.vignetteStretch = 0;
  41140. /**
  41141. * Vignette centre X Offset.
  41142. */
  41143. this.vignetteCentreX = 0;
  41144. /**
  41145. * Vignette centre Y Offset.
  41146. */
  41147. this.vignetteCentreY = 0;
  41148. /**
  41149. * Vignette weight or intensity of the vignette effect.
  41150. */
  41151. this.vignetteWeight = 1.5;
  41152. /**
  41153. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41154. * if vignetteEnabled is set to true.
  41155. */
  41156. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41157. /**
  41158. * Camera field of view used by the Vignette effect.
  41159. */
  41160. this.vignetteCameraFov = 0.5;
  41161. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41162. this._vignetteEnabled = false;
  41163. this._applyByPostProcess = false;
  41164. this._isEnabled = true;
  41165. /**
  41166. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41167. */
  41168. this.onUpdateParameters = new BABYLON.Observable();
  41169. }
  41170. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41171. /**
  41172. * Gets wether the color curves effect is enabled.
  41173. */
  41174. get: function () {
  41175. return this._colorCurvesEnabled;
  41176. },
  41177. /**
  41178. * Sets wether the color curves effect is enabled.
  41179. */
  41180. set: function (value) {
  41181. if (this._colorCurvesEnabled === value) {
  41182. return;
  41183. }
  41184. this._colorCurvesEnabled = value;
  41185. this._updateParameters();
  41186. },
  41187. enumerable: true,
  41188. configurable: true
  41189. });
  41190. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41191. /**
  41192. * Gets wether the color grading effect is enabled.
  41193. */
  41194. get: function () {
  41195. return this._colorGradingEnabled;
  41196. },
  41197. /**
  41198. * Sets wether the color grading effect is enabled.
  41199. */
  41200. set: function (value) {
  41201. if (this._colorGradingEnabled === value) {
  41202. return;
  41203. }
  41204. this._colorGradingEnabled = value;
  41205. this._updateParameters();
  41206. },
  41207. enumerable: true,
  41208. configurable: true
  41209. });
  41210. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41211. /**
  41212. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41213. */
  41214. get: function () {
  41215. return this._colorGradingWithGreenDepth;
  41216. },
  41217. /**
  41218. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41219. */
  41220. set: function (value) {
  41221. if (this._colorGradingWithGreenDepth === value) {
  41222. return;
  41223. }
  41224. this._colorGradingWithGreenDepth = value;
  41225. this._updateParameters();
  41226. },
  41227. enumerable: true,
  41228. configurable: true
  41229. });
  41230. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41231. /**
  41232. * Gets wether the color grading texture contains BGR values.
  41233. */
  41234. get: function () {
  41235. return this._colorGradingBGR;
  41236. },
  41237. /**
  41238. * Sets wether the color grading texture contains BGR values.
  41239. */
  41240. set: function (value) {
  41241. if (this._colorGradingBGR === value) {
  41242. return;
  41243. }
  41244. this._colorGradingBGR = value;
  41245. this._updateParameters();
  41246. },
  41247. enumerable: true,
  41248. configurable: true
  41249. });
  41250. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41251. /**
  41252. * Gets the Exposure used in the effect.
  41253. */
  41254. get: function () {
  41255. return this._exposure;
  41256. },
  41257. /**
  41258. * Sets the Exposure used in the effect.
  41259. */
  41260. set: function (value) {
  41261. if (this._exposure === value) {
  41262. return;
  41263. }
  41264. this._exposure = value;
  41265. this._updateParameters();
  41266. },
  41267. enumerable: true,
  41268. configurable: true
  41269. });
  41270. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41271. /**
  41272. * Gets wether the tone mapping effect is enabled.
  41273. */
  41274. get: function () {
  41275. return this._toneMappingEnabled;
  41276. },
  41277. /**
  41278. * Sets wether the tone mapping effect is enabled.
  41279. */
  41280. set: function (value) {
  41281. if (this._toneMappingEnabled === value) {
  41282. return;
  41283. }
  41284. this._toneMappingEnabled = value;
  41285. this._updateParameters();
  41286. },
  41287. enumerable: true,
  41288. configurable: true
  41289. });
  41290. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41291. /**
  41292. * Gets the contrast used in the effect.
  41293. */
  41294. get: function () {
  41295. return this._contrast;
  41296. },
  41297. /**
  41298. * Sets the contrast used in the effect.
  41299. */
  41300. set: function (value) {
  41301. if (this._contrast === value) {
  41302. return;
  41303. }
  41304. this._contrast = value;
  41305. this._updateParameters();
  41306. },
  41307. enumerable: true,
  41308. configurable: true
  41309. });
  41310. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41311. /**
  41312. * Gets the vignette blend mode allowing different kind of effect.
  41313. */
  41314. get: function () {
  41315. return this._vignetteBlendMode;
  41316. },
  41317. /**
  41318. * Sets the vignette blend mode allowing different kind of effect.
  41319. */
  41320. set: function (value) {
  41321. if (this._vignetteBlendMode === value) {
  41322. return;
  41323. }
  41324. this._vignetteBlendMode = value;
  41325. this._updateParameters();
  41326. },
  41327. enumerable: true,
  41328. configurable: true
  41329. });
  41330. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41331. /**
  41332. * Gets wether the vignette effect is enabled.
  41333. */
  41334. get: function () {
  41335. return this._vignetteEnabled;
  41336. },
  41337. /**
  41338. * Sets wether the vignette effect is enabled.
  41339. */
  41340. set: function (value) {
  41341. if (this._vignetteEnabled === value) {
  41342. return;
  41343. }
  41344. this._vignetteEnabled = value;
  41345. this._updateParameters();
  41346. },
  41347. enumerable: true,
  41348. configurable: true
  41349. });
  41350. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41351. /**
  41352. * Gets wether the image processing is applied through a post process or not.
  41353. */
  41354. get: function () {
  41355. return this._applyByPostProcess;
  41356. },
  41357. /**
  41358. * Sets wether the image processing is applied through a post process or not.
  41359. */
  41360. set: function (value) {
  41361. if (this._applyByPostProcess === value) {
  41362. return;
  41363. }
  41364. this._applyByPostProcess = value;
  41365. this._updateParameters();
  41366. },
  41367. enumerable: true,
  41368. configurable: true
  41369. });
  41370. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41371. /**
  41372. * Gets wether the image processing is enabled or not.
  41373. */
  41374. get: function () {
  41375. return this._isEnabled;
  41376. },
  41377. /**
  41378. * Sets wether the image processing is enabled or not.
  41379. */
  41380. set: function (value) {
  41381. if (this._isEnabled === value) {
  41382. return;
  41383. }
  41384. this._isEnabled = value;
  41385. this._updateParameters();
  41386. },
  41387. enumerable: true,
  41388. configurable: true
  41389. });
  41390. /**
  41391. * Method called each time the image processing information changes requires to recompile the effect.
  41392. */
  41393. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41394. this.onUpdateParameters.notifyObservers(this);
  41395. };
  41396. ImageProcessingConfiguration.prototype.getClassName = function () {
  41397. return "ImageProcessingConfiguration";
  41398. };
  41399. /**
  41400. * Prepare the list of uniforms associated with the Image Processing effects.
  41401. * @param uniformsList The list of uniforms used in the effect
  41402. * @param defines the list of defines currently in use
  41403. */
  41404. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41405. if (defines.EXPOSURE) {
  41406. uniforms.push("exposureLinear");
  41407. }
  41408. if (defines.CONTRAST) {
  41409. uniforms.push("contrast");
  41410. }
  41411. if (defines.COLORGRADING) {
  41412. uniforms.push("colorTransformSettings");
  41413. }
  41414. if (defines.VIGNETTE) {
  41415. uniforms.push("vInverseScreenSize");
  41416. uniforms.push("vignetteSettings1");
  41417. uniforms.push("vignetteSettings2");
  41418. }
  41419. if (defines.COLORCURVES) {
  41420. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41421. }
  41422. };
  41423. /**
  41424. * Prepare the list of samplers associated with the Image Processing effects.
  41425. * @param uniformsList The list of uniforms used in the effect
  41426. * @param defines the list of defines currently in use
  41427. */
  41428. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41429. if (defines.COLORGRADING) {
  41430. samplersList.push("txColorTransform");
  41431. }
  41432. };
  41433. /**
  41434. * Prepare the list of defines associated to the shader.
  41435. * @param defines the list of defines to complete
  41436. */
  41437. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41438. if (forPostProcess === void 0) { forPostProcess = false; }
  41439. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41440. defines.VIGNETTE = false;
  41441. defines.TONEMAPPING = false;
  41442. defines.CONTRAST = false;
  41443. defines.EXPOSURE = false;
  41444. defines.COLORCURVES = false;
  41445. defines.COLORGRADING = false;
  41446. defines.COLORGRADING3D = false;
  41447. defines.IMAGEPROCESSING = false;
  41448. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41449. return;
  41450. }
  41451. defines.VIGNETTE = this.vignetteEnabled;
  41452. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41453. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41454. defines.TONEMAPPING = this.toneMappingEnabled;
  41455. defines.CONTRAST = (this.contrast !== 1.0);
  41456. defines.EXPOSURE = (this.exposure !== 1.0);
  41457. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41458. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41459. if (defines.COLORGRADING) {
  41460. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41461. }
  41462. else {
  41463. defines.COLORGRADING3D = false;
  41464. }
  41465. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41466. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41467. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41468. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41469. };
  41470. /**
  41471. * Returns true if all the image processing information are ready.
  41472. */
  41473. ImageProcessingConfiguration.prototype.isReady = function () {
  41474. // Color Grading texure can not be none blocking.
  41475. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41476. };
  41477. /**
  41478. * Binds the image processing to the shader.
  41479. * @param effect The effect to bind to
  41480. */
  41481. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41482. if (aspectRatio === void 0) { aspectRatio = 1; }
  41483. // Color Curves
  41484. if (this._colorCurvesEnabled && this.colorCurves) {
  41485. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41486. }
  41487. // Vignette
  41488. if (this._vignetteEnabled) {
  41489. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41490. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41491. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41492. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41493. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41494. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41495. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41496. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41497. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41498. var vignettePower = -2.0 * this.vignetteWeight;
  41499. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41500. }
  41501. // Exposure
  41502. effect.setFloat("exposureLinear", this.exposure);
  41503. // Contrast
  41504. effect.setFloat("contrast", this.contrast);
  41505. // Color transform settings
  41506. if (this.colorGradingTexture) {
  41507. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41508. var textureSize = this.colorGradingTexture.getSize().height;
  41509. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41510. 0.5 / textureSize, // textureOffset
  41511. textureSize, // textureSize
  41512. this.colorGradingTexture.level // weight
  41513. );
  41514. }
  41515. };
  41516. /**
  41517. * Clones the current image processing instance.
  41518. * @return The cloned image processing
  41519. */
  41520. ImageProcessingConfiguration.prototype.clone = function () {
  41521. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41522. };
  41523. /**
  41524. * Serializes the current image processing instance to a json representation.
  41525. * @return a JSON representation
  41526. */
  41527. ImageProcessingConfiguration.prototype.serialize = function () {
  41528. return BABYLON.SerializationHelper.Serialize(this);
  41529. };
  41530. /**
  41531. * Parses the image processing from a json representation.
  41532. * @param source the JSON source to parse
  41533. * @return The parsed image processing
  41534. */
  41535. ImageProcessingConfiguration.Parse = function (source) {
  41536. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41537. };
  41538. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41539. /**
  41540. * Used to apply the vignette as a mix with the pixel color.
  41541. */
  41542. get: function () {
  41543. return this._VIGNETTEMODE_MULTIPLY;
  41544. },
  41545. enumerable: true,
  41546. configurable: true
  41547. });
  41548. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41549. /**
  41550. * Used to apply the vignette as a replacement of the pixel color.
  41551. */
  41552. get: function () {
  41553. return this._VIGNETTEMODE_OPAQUE;
  41554. },
  41555. enumerable: true,
  41556. configurable: true
  41557. });
  41558. // Static constants associated to the image processing.
  41559. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41560. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41561. __decorate([
  41562. BABYLON.serializeAsColorCurves()
  41563. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41564. __decorate([
  41565. BABYLON.serialize()
  41566. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41567. __decorate([
  41568. BABYLON.serializeAsTexture()
  41569. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41570. __decorate([
  41571. BABYLON.serialize()
  41572. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41573. __decorate([
  41574. BABYLON.serialize()
  41575. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41576. __decorate([
  41577. BABYLON.serialize()
  41578. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41579. __decorate([
  41580. BABYLON.serialize()
  41581. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41582. __decorate([
  41583. BABYLON.serialize()
  41584. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41585. __decorate([
  41586. BABYLON.serialize()
  41587. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41588. __decorate([
  41589. BABYLON.serialize()
  41590. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41591. __decorate([
  41592. BABYLON.serialize()
  41593. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41594. __decorate([
  41595. BABYLON.serialize()
  41596. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41597. __decorate([
  41598. BABYLON.serialize()
  41599. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41600. __decorate([
  41601. BABYLON.serializeAsColor4()
  41602. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41603. __decorate([
  41604. BABYLON.serialize()
  41605. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41606. __decorate([
  41607. BABYLON.serialize()
  41608. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41609. __decorate([
  41610. BABYLON.serialize()
  41611. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41612. __decorate([
  41613. BABYLON.serialize()
  41614. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41615. __decorate([
  41616. BABYLON.serialize()
  41617. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41618. return ImageProcessingConfiguration;
  41619. }());
  41620. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41621. })(BABYLON || (BABYLON = {}));
  41622. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41623. var BABYLON;
  41624. (function (BABYLON) {
  41625. /**
  41626. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41627. * It can help converting any input color in a desired output one. This can then be used to create effects
  41628. * from sepia, black and white to sixties or futuristic rendering...
  41629. *
  41630. * The only supported format is currently 3dl.
  41631. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41632. */
  41633. var ColorGradingTexture = /** @class */ (function (_super) {
  41634. __extends(ColorGradingTexture, _super);
  41635. /**
  41636. * Instantiates a ColorGradingTexture from the following parameters.
  41637. *
  41638. * @param url The location of the color gradind data (currently only supporting 3dl)
  41639. * @param scene The scene the texture will be used in
  41640. */
  41641. function ColorGradingTexture(url, scene) {
  41642. var _this = _super.call(this, scene) || this;
  41643. if (!url) {
  41644. return _this;
  41645. }
  41646. _this._engine = scene.getEngine();
  41647. _this._textureMatrix = BABYLON.Matrix.Identity();
  41648. _this.name = url;
  41649. _this.url = url;
  41650. _this.hasAlpha = false;
  41651. _this.isCube = false;
  41652. _this.is3D = _this._engine.webGLVersion > 1;
  41653. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41654. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41655. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41656. _this.anisotropicFilteringLevel = 1;
  41657. _this._texture = _this._getFromCache(url, true);
  41658. if (!_this._texture) {
  41659. if (!scene.useDelayedTextureLoading) {
  41660. _this.loadTexture();
  41661. }
  41662. else {
  41663. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41664. }
  41665. }
  41666. return _this;
  41667. }
  41668. /**
  41669. * Returns the texture matrix used in most of the material.
  41670. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41671. */
  41672. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41673. return this._textureMatrix;
  41674. };
  41675. /**
  41676. * Occurs when the file being loaded is a .3dl LUT file.
  41677. */
  41678. ColorGradingTexture.prototype.load3dlTexture = function () {
  41679. var engine = this._engine;
  41680. var texture;
  41681. if (engine.webGLVersion === 1) {
  41682. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41683. }
  41684. else {
  41685. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41686. }
  41687. this._texture = texture;
  41688. var callback = function (text) {
  41689. if (typeof text !== "string") {
  41690. return;
  41691. }
  41692. var data = null;
  41693. var tempData = null;
  41694. var line;
  41695. var lines = text.split('\n');
  41696. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41697. var maxColor = 0;
  41698. for (var i = 0; i < lines.length; i++) {
  41699. line = lines[i];
  41700. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41701. continue;
  41702. if (line.indexOf('#') === 0)
  41703. continue;
  41704. var words = line.split(" ");
  41705. if (size === 0) {
  41706. // Number of space + one
  41707. size = words.length;
  41708. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41709. tempData = new Float32Array(size * size * size * 4);
  41710. continue;
  41711. }
  41712. if (size != 0) {
  41713. var r = Math.max(parseInt(words[0]), 0);
  41714. var g = Math.max(parseInt(words[1]), 0);
  41715. var b = Math.max(parseInt(words[2]), 0);
  41716. maxColor = Math.max(r, maxColor);
  41717. maxColor = Math.max(g, maxColor);
  41718. maxColor = Math.max(b, maxColor);
  41719. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41720. if (tempData) {
  41721. tempData[pixelStorageIndex + 0] = r;
  41722. tempData[pixelStorageIndex + 1] = g;
  41723. tempData[pixelStorageIndex + 2] = b;
  41724. }
  41725. pixelIndexSlice++;
  41726. if (pixelIndexSlice % size == 0) {
  41727. pixelIndexH++;
  41728. pixelIndexSlice = 0;
  41729. if (pixelIndexH % size == 0) {
  41730. pixelIndexW++;
  41731. pixelIndexH = 0;
  41732. }
  41733. }
  41734. }
  41735. }
  41736. if (tempData && data) {
  41737. for (var i = 0; i < tempData.length; i++) {
  41738. if (i > 0 && (i + 1) % 4 === 0) {
  41739. data[i] = 255;
  41740. }
  41741. else {
  41742. var value = tempData[i];
  41743. data[i] = (value / maxColor * 255);
  41744. }
  41745. }
  41746. }
  41747. if (texture.is3D) {
  41748. texture.updateSize(size, size, size);
  41749. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41750. }
  41751. else {
  41752. texture.updateSize(size * size, size);
  41753. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41754. }
  41755. };
  41756. var scene = this.getScene();
  41757. if (scene) {
  41758. scene._loadFile(this.url, callback);
  41759. }
  41760. else {
  41761. this._engine._loadFile(this.url, callback);
  41762. }
  41763. return this._texture;
  41764. };
  41765. /**
  41766. * Starts the loading process of the texture.
  41767. */
  41768. ColorGradingTexture.prototype.loadTexture = function () {
  41769. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41770. this.load3dlTexture();
  41771. }
  41772. };
  41773. /**
  41774. * Clones the color gradind texture.
  41775. */
  41776. ColorGradingTexture.prototype.clone = function () {
  41777. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41778. // Base texture
  41779. newTexture.level = this.level;
  41780. return newTexture;
  41781. };
  41782. /**
  41783. * Called during delayed load for textures.
  41784. */
  41785. ColorGradingTexture.prototype.delayLoad = function () {
  41786. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41787. return;
  41788. }
  41789. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41790. this._texture = this._getFromCache(this.url, true);
  41791. if (!this._texture) {
  41792. this.loadTexture();
  41793. }
  41794. };
  41795. /**
  41796. * Parses a color grading texture serialized by Babylon.
  41797. * @param parsedTexture The texture information being parsedTexture
  41798. * @param scene The scene to load the texture in
  41799. * @param rootUrl The root url of the data assets to load
  41800. * @return A color gradind texture
  41801. */
  41802. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41803. var texture = null;
  41804. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41805. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41806. texture.name = parsedTexture.name;
  41807. texture.level = parsedTexture.level;
  41808. }
  41809. return texture;
  41810. };
  41811. /**
  41812. * Serializes the LUT texture to json format.
  41813. */
  41814. ColorGradingTexture.prototype.serialize = function () {
  41815. if (!this.name) {
  41816. return null;
  41817. }
  41818. var serializationObject = {};
  41819. serializationObject.name = this.name;
  41820. serializationObject.level = this.level;
  41821. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41822. return serializationObject;
  41823. };
  41824. /**
  41825. * Empty line regex stored for GC.
  41826. */
  41827. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41828. return ColorGradingTexture;
  41829. }(BABYLON.BaseTexture));
  41830. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41831. })(BABYLON || (BABYLON = {}));
  41832. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41833. var BABYLON;
  41834. (function (BABYLON) {
  41835. /**
  41836. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41837. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41838. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  41839. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41840. */
  41841. var ColorCurves = /** @class */ (function () {
  41842. function ColorCurves() {
  41843. this._dirty = true;
  41844. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41845. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41846. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41847. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41848. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41849. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41850. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41851. this._globalHue = 30;
  41852. this._globalDensity = 0;
  41853. this._globalSaturation = 0;
  41854. this._globalExposure = 0;
  41855. this._highlightsHue = 30;
  41856. this._highlightsDensity = 0;
  41857. this._highlightsSaturation = 0;
  41858. this._highlightsExposure = 0;
  41859. this._midtonesHue = 30;
  41860. this._midtonesDensity = 0;
  41861. this._midtonesSaturation = 0;
  41862. this._midtonesExposure = 0;
  41863. this._shadowsHue = 30;
  41864. this._shadowsDensity = 0;
  41865. this._shadowsSaturation = 0;
  41866. this._shadowsExposure = 0;
  41867. }
  41868. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41869. /**
  41870. * Gets the global Hue value.
  41871. * 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).
  41872. */
  41873. get: function () {
  41874. return this._globalHue;
  41875. },
  41876. /**
  41877. * Sets the global Hue value.
  41878. * 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).
  41879. */
  41880. set: function (value) {
  41881. this._globalHue = value;
  41882. this._dirty = true;
  41883. },
  41884. enumerable: true,
  41885. configurable: true
  41886. });
  41887. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41888. /**
  41889. * Gets the global Density value.
  41890. * 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.
  41891. * Values less than zero provide a filter of opposite hue.
  41892. */
  41893. get: function () {
  41894. return this._globalDensity;
  41895. },
  41896. /**
  41897. * Sets the global Density value.
  41898. * 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.
  41899. * Values less than zero provide a filter of opposite hue.
  41900. */
  41901. set: function (value) {
  41902. this._globalDensity = value;
  41903. this._dirty = true;
  41904. },
  41905. enumerable: true,
  41906. configurable: true
  41907. });
  41908. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41909. /**
  41910. * Gets the global Saturation value.
  41911. * 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.
  41912. */
  41913. get: function () {
  41914. return this._globalSaturation;
  41915. },
  41916. /**
  41917. * Sets the global Saturation value.
  41918. * 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.
  41919. */
  41920. set: function (value) {
  41921. this._globalSaturation = value;
  41922. this._dirty = true;
  41923. },
  41924. enumerable: true,
  41925. configurable: true
  41926. });
  41927. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41928. /**
  41929. * Gets the global Exposure value.
  41930. * 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.
  41931. */
  41932. get: function () {
  41933. return this._globalExposure;
  41934. },
  41935. /**
  41936. * Sets the global Exposure value.
  41937. * 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.
  41938. */
  41939. set: function (value) {
  41940. this._globalExposure = value;
  41941. this._dirty = true;
  41942. },
  41943. enumerable: true,
  41944. configurable: true
  41945. });
  41946. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41947. /**
  41948. * Gets the highlights Hue value.
  41949. * 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).
  41950. */
  41951. get: function () {
  41952. return this._highlightsHue;
  41953. },
  41954. /**
  41955. * Sets the highlights Hue value.
  41956. * 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).
  41957. */
  41958. set: function (value) {
  41959. this._highlightsHue = value;
  41960. this._dirty = true;
  41961. },
  41962. enumerable: true,
  41963. configurable: true
  41964. });
  41965. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41966. /**
  41967. * Gets the highlights Density value.
  41968. * 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.
  41969. * Values less than zero provide a filter of opposite hue.
  41970. */
  41971. get: function () {
  41972. return this._highlightsDensity;
  41973. },
  41974. /**
  41975. * Sets the highlights Density value.
  41976. * 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.
  41977. * Values less than zero provide a filter of opposite hue.
  41978. */
  41979. set: function (value) {
  41980. this._highlightsDensity = value;
  41981. this._dirty = true;
  41982. },
  41983. enumerable: true,
  41984. configurable: true
  41985. });
  41986. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41987. /**
  41988. * Gets the highlights Saturation value.
  41989. * 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.
  41990. */
  41991. get: function () {
  41992. return this._highlightsSaturation;
  41993. },
  41994. /**
  41995. * Sets the highlights Saturation value.
  41996. * 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.
  41997. */
  41998. set: function (value) {
  41999. this._highlightsSaturation = value;
  42000. this._dirty = true;
  42001. },
  42002. enumerable: true,
  42003. configurable: true
  42004. });
  42005. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42006. /**
  42007. * Gets the highlights Exposure value.
  42008. * 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.
  42009. */
  42010. get: function () {
  42011. return this._highlightsExposure;
  42012. },
  42013. /**
  42014. * Sets the highlights Exposure value.
  42015. * 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.
  42016. */
  42017. set: function (value) {
  42018. this._highlightsExposure = value;
  42019. this._dirty = true;
  42020. },
  42021. enumerable: true,
  42022. configurable: true
  42023. });
  42024. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42025. /**
  42026. * Gets the midtones Hue value.
  42027. * 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).
  42028. */
  42029. get: function () {
  42030. return this._midtonesHue;
  42031. },
  42032. /**
  42033. * Sets the midtones Hue value.
  42034. * 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).
  42035. */
  42036. set: function (value) {
  42037. this._midtonesHue = value;
  42038. this._dirty = true;
  42039. },
  42040. enumerable: true,
  42041. configurable: true
  42042. });
  42043. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42044. /**
  42045. * Gets the midtones Density value.
  42046. * 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.
  42047. * Values less than zero provide a filter of opposite hue.
  42048. */
  42049. get: function () {
  42050. return this._midtonesDensity;
  42051. },
  42052. /**
  42053. * Sets the midtones Density value.
  42054. * 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.
  42055. * Values less than zero provide a filter of opposite hue.
  42056. */
  42057. set: function (value) {
  42058. this._midtonesDensity = value;
  42059. this._dirty = true;
  42060. },
  42061. enumerable: true,
  42062. configurable: true
  42063. });
  42064. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42065. /**
  42066. * Gets the midtones Saturation value.
  42067. * 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.
  42068. */
  42069. get: function () {
  42070. return this._midtonesSaturation;
  42071. },
  42072. /**
  42073. * Sets the midtones Saturation value.
  42074. * 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.
  42075. */
  42076. set: function (value) {
  42077. this._midtonesSaturation = value;
  42078. this._dirty = true;
  42079. },
  42080. enumerable: true,
  42081. configurable: true
  42082. });
  42083. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42084. /**
  42085. * Gets the midtones Exposure value.
  42086. * 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.
  42087. */
  42088. get: function () {
  42089. return this._midtonesExposure;
  42090. },
  42091. /**
  42092. * Sets the midtones Exposure value.
  42093. * 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.
  42094. */
  42095. set: function (value) {
  42096. this._midtonesExposure = value;
  42097. this._dirty = true;
  42098. },
  42099. enumerable: true,
  42100. configurable: true
  42101. });
  42102. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42103. /**
  42104. * Gets the shadows Hue value.
  42105. * 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).
  42106. */
  42107. get: function () {
  42108. return this._shadowsHue;
  42109. },
  42110. /**
  42111. * Sets the shadows Hue value.
  42112. * 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).
  42113. */
  42114. set: function (value) {
  42115. this._shadowsHue = value;
  42116. this._dirty = true;
  42117. },
  42118. enumerable: true,
  42119. configurable: true
  42120. });
  42121. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42122. /**
  42123. * Gets the shadows Density value.
  42124. * 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.
  42125. * Values less than zero provide a filter of opposite hue.
  42126. */
  42127. get: function () {
  42128. return this._shadowsDensity;
  42129. },
  42130. /**
  42131. * Sets the shadows Density value.
  42132. * 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.
  42133. * Values less than zero provide a filter of opposite hue.
  42134. */
  42135. set: function (value) {
  42136. this._shadowsDensity = value;
  42137. this._dirty = true;
  42138. },
  42139. enumerable: true,
  42140. configurable: true
  42141. });
  42142. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42143. /**
  42144. * Gets the shadows Saturation value.
  42145. * 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.
  42146. */
  42147. get: function () {
  42148. return this._shadowsSaturation;
  42149. },
  42150. /**
  42151. * Sets the shadows Saturation value.
  42152. * 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.
  42153. */
  42154. set: function (value) {
  42155. this._shadowsSaturation = value;
  42156. this._dirty = true;
  42157. },
  42158. enumerable: true,
  42159. configurable: true
  42160. });
  42161. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42162. /**
  42163. * Gets the shadows Exposure value.
  42164. * 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.
  42165. */
  42166. get: function () {
  42167. return this._shadowsExposure;
  42168. },
  42169. /**
  42170. * Sets the shadows Exposure value.
  42171. * 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.
  42172. */
  42173. set: function (value) {
  42174. this._shadowsExposure = value;
  42175. this._dirty = true;
  42176. },
  42177. enumerable: true,
  42178. configurable: true
  42179. });
  42180. ColorCurves.prototype.getClassName = function () {
  42181. return "ColorCurves";
  42182. };
  42183. /**
  42184. * Binds the color curves to the shader.
  42185. * @param colorCurves The color curve to bind
  42186. * @param effect The effect to bind to
  42187. */
  42188. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42189. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42190. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42191. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42192. if (colorCurves._dirty) {
  42193. colorCurves._dirty = false;
  42194. // Fill in global info.
  42195. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42196. // Compute highlights info.
  42197. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42198. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42199. // Compute midtones info.
  42200. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42201. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42202. // Compute shadows info.
  42203. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42204. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42205. // Compute deltas (neutral is midtones).
  42206. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42207. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42208. }
  42209. if (effect) {
  42210. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42211. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42212. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42213. }
  42214. };
  42215. /**
  42216. * Prepare the list of uniforms associated with the ColorCurves effects.
  42217. * @param uniformsList The list of uniforms used in the effect
  42218. */
  42219. ColorCurves.PrepareUniforms = function (uniformsList) {
  42220. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42221. };
  42222. /**
  42223. * Returns color grading data based on a hue, density, saturation and exposure value.
  42224. * @param filterHue The hue of the color filter.
  42225. * @param filterDensity The density of the color filter.
  42226. * @param saturation The saturation.
  42227. * @param exposure The exposure.
  42228. * @param result The result data container.
  42229. */
  42230. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42231. if (hue == null) {
  42232. return;
  42233. }
  42234. hue = ColorCurves.clamp(hue, 0, 360);
  42235. density = ColorCurves.clamp(density, -100, 100);
  42236. saturation = ColorCurves.clamp(saturation, -100, 100);
  42237. exposure = ColorCurves.clamp(exposure, -100, 100);
  42238. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42239. // so that the maximum filter density is only 50% control. This provides fine control
  42240. // for small values and reasonable range.
  42241. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42242. density *= 0.5;
  42243. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42244. if (density < 0) {
  42245. density *= -1;
  42246. hue = (hue + 180) % 360;
  42247. }
  42248. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42249. result.scaleToRef(2, result);
  42250. result.a = 1 + 0.01 * saturation;
  42251. };
  42252. /**
  42253. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42254. * @param value The input slider value in range [-100,100].
  42255. * @returns Adjusted value.
  42256. */
  42257. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42258. value /= 100;
  42259. var x = Math.abs(value);
  42260. x = Math.pow(x, 2);
  42261. if (value < 0) {
  42262. x *= -1;
  42263. }
  42264. x *= 100;
  42265. return x;
  42266. };
  42267. /**
  42268. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42269. * @param hue The hue (H) input.
  42270. * @param saturation The saturation (S) input.
  42271. * @param brightness The brightness (B) input.
  42272. * @result An RGBA color represented as Vector4.
  42273. */
  42274. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42275. var h = ColorCurves.clamp(hue, 0, 360);
  42276. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42277. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42278. if (s === 0) {
  42279. result.r = v;
  42280. result.g = v;
  42281. result.b = v;
  42282. }
  42283. else {
  42284. // sector 0 to 5
  42285. h /= 60;
  42286. var i = Math.floor(h);
  42287. // fractional part of h
  42288. var f = h - i;
  42289. var p = v * (1 - s);
  42290. var q = v * (1 - s * f);
  42291. var t = v * (1 - s * (1 - f));
  42292. switch (i) {
  42293. case 0:
  42294. result.r = v;
  42295. result.g = t;
  42296. result.b = p;
  42297. break;
  42298. case 1:
  42299. result.r = q;
  42300. result.g = v;
  42301. result.b = p;
  42302. break;
  42303. case 2:
  42304. result.r = p;
  42305. result.g = v;
  42306. result.b = t;
  42307. break;
  42308. case 3:
  42309. result.r = p;
  42310. result.g = q;
  42311. result.b = v;
  42312. break;
  42313. case 4:
  42314. result.r = t;
  42315. result.g = p;
  42316. result.b = v;
  42317. break;
  42318. default: // case 5:
  42319. result.r = v;
  42320. result.g = p;
  42321. result.b = q;
  42322. break;
  42323. }
  42324. }
  42325. result.a = 1;
  42326. };
  42327. /**
  42328. * Returns a value clamped between min and max
  42329. * @param value The value to clamp
  42330. * @param min The minimum of value
  42331. * @param max The maximum of value
  42332. * @returns The clamped value.
  42333. */
  42334. ColorCurves.clamp = function (value, min, max) {
  42335. return Math.min(Math.max(value, min), max);
  42336. };
  42337. /**
  42338. * Clones the current color curve instance.
  42339. * @return The cloned curves
  42340. */
  42341. ColorCurves.prototype.clone = function () {
  42342. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42343. };
  42344. /**
  42345. * Serializes the current color curve instance to a json representation.
  42346. * @return a JSON representation
  42347. */
  42348. ColorCurves.prototype.serialize = function () {
  42349. return BABYLON.SerializationHelper.Serialize(this);
  42350. };
  42351. /**
  42352. * Parses the color curve from a json representation.
  42353. * @param source the JSON source to parse
  42354. * @return The parsed curves
  42355. */
  42356. ColorCurves.Parse = function (source) {
  42357. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42358. };
  42359. __decorate([
  42360. BABYLON.serialize()
  42361. ], ColorCurves.prototype, "_globalHue", void 0);
  42362. __decorate([
  42363. BABYLON.serialize()
  42364. ], ColorCurves.prototype, "_globalDensity", void 0);
  42365. __decorate([
  42366. BABYLON.serialize()
  42367. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42368. __decorate([
  42369. BABYLON.serialize()
  42370. ], ColorCurves.prototype, "_globalExposure", void 0);
  42371. __decorate([
  42372. BABYLON.serialize()
  42373. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42374. __decorate([
  42375. BABYLON.serialize()
  42376. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42377. __decorate([
  42378. BABYLON.serialize()
  42379. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42380. __decorate([
  42381. BABYLON.serialize()
  42382. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42383. __decorate([
  42384. BABYLON.serialize()
  42385. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42386. __decorate([
  42387. BABYLON.serialize()
  42388. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42389. __decorate([
  42390. BABYLON.serialize()
  42391. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42392. __decorate([
  42393. BABYLON.serialize()
  42394. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42395. return ColorCurves;
  42396. }());
  42397. BABYLON.ColorCurves = ColorCurves;
  42398. })(BABYLON || (BABYLON = {}));
  42399. //# sourceMappingURL=babylon.colorCurves.js.map
  42400. //# sourceMappingURL=babylon.behavior.js.map
  42401. var BABYLON;
  42402. (function (BABYLON) {
  42403. /**
  42404. * "Static Class" containing the most commonly used helper while dealing with material for
  42405. * rendering purpose.
  42406. *
  42407. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42408. *
  42409. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42410. */
  42411. var MaterialHelper = /** @class */ (function () {
  42412. function MaterialHelper() {
  42413. }
  42414. /**
  42415. * Bind the current view position to an effect.
  42416. * @param effect The effect to be bound
  42417. * @param scene The scene the eyes position is used from
  42418. */
  42419. MaterialHelper.BindEyePosition = function (effect, scene) {
  42420. if (scene._forcedViewPosition) {
  42421. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42422. return;
  42423. }
  42424. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42425. };
  42426. /**
  42427. * Helps preparing the defines values about the UVs in used in the effect.
  42428. * UVs are shared as much as we can accross chanels in the shaders.
  42429. * @param texture The texture we are preparing the UVs for
  42430. * @param defines The defines to update
  42431. * @param key The chanel key "diffuse", "specular"... used in the shader
  42432. */
  42433. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42434. defines._needUVs = true;
  42435. defines[key] = true;
  42436. if (texture.getTextureMatrix().isIdentity(true)) {
  42437. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42438. if (texture.coordinatesIndex === 0) {
  42439. defines["MAINUV1"] = true;
  42440. }
  42441. else {
  42442. defines["MAINUV2"] = true;
  42443. }
  42444. }
  42445. else {
  42446. defines[key + "DIRECTUV"] = 0;
  42447. }
  42448. };
  42449. /**
  42450. * Binds a texture matrix value to its corrsponding uniform
  42451. * @param texture The texture to bind the matrix for
  42452. * @param uniformBuffer The uniform buffer receivin the data
  42453. * @param key The chanel key "diffuse", "specular"... used in the shader
  42454. */
  42455. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42456. var matrix = texture.getTextureMatrix();
  42457. if (!matrix.isIdentity(true)) {
  42458. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42459. }
  42460. };
  42461. /**
  42462. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42463. * @param mesh defines the current mesh
  42464. * @param scene defines the current scene
  42465. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42466. * @param pointsCloud defines if point cloud rendering has to be turned on
  42467. * @param fogEnabled defines if fog has to be turned on
  42468. * @param alphaTest defines if alpha testing has to be turned on
  42469. * @param defines defines the current list of defines
  42470. */
  42471. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42472. if (defines._areMiscDirty) {
  42473. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42474. defines["POINTSIZE"] = pointsCloud;
  42475. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42476. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42477. defines["ALPHATEST"] = alphaTest;
  42478. }
  42479. };
  42480. /**
  42481. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42482. * @param scene defines the current scene
  42483. * @param engine defines the current engine
  42484. * @param defines specifies the list of active defines
  42485. * @param useInstances defines if instances have to be turned on
  42486. * @param useClipPlane defines if clip plane have to be turned on
  42487. */
  42488. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42489. if (useClipPlane === void 0) { useClipPlane = null; }
  42490. var changed = false;
  42491. if (useClipPlane == null) {
  42492. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42493. }
  42494. if (defines["CLIPPLANE"] !== useClipPlane) {
  42495. defines["CLIPPLANE"] = useClipPlane;
  42496. changed = true;
  42497. }
  42498. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42499. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42500. changed = true;
  42501. }
  42502. if (defines["INSTANCES"] !== useInstances) {
  42503. defines["INSTANCES"] = useInstances;
  42504. changed = true;
  42505. }
  42506. if (changed) {
  42507. defines.markAsUnprocessed();
  42508. }
  42509. };
  42510. /**
  42511. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42512. * @param mesh The mesh containing the geometry data we will draw
  42513. * @param defines The defines to update
  42514. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42515. * @param useBones Precise whether bones should be used or not (override mesh info)
  42516. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42517. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42518. * @returns false if defines are considered not dirty and have not been checked
  42519. */
  42520. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42521. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42522. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42523. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42524. return false;
  42525. }
  42526. defines._normals = defines._needNormals;
  42527. defines._uvs = defines._needUVs;
  42528. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42529. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42530. defines["TANGENT"] = true;
  42531. }
  42532. if (defines._needUVs) {
  42533. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42534. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42535. }
  42536. else {
  42537. defines["UV1"] = false;
  42538. defines["UV2"] = false;
  42539. }
  42540. if (useVertexColor) {
  42541. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42542. defines["VERTEXCOLOR"] = hasVertexColors;
  42543. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42544. }
  42545. if (useBones) {
  42546. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42547. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42548. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42549. }
  42550. else {
  42551. defines["NUM_BONE_INFLUENCERS"] = 0;
  42552. defines["BonesPerMesh"] = 0;
  42553. }
  42554. }
  42555. if (useMorphTargets) {
  42556. var manager = mesh.morphTargetManager;
  42557. if (manager) {
  42558. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42559. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42560. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42561. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42562. }
  42563. else {
  42564. defines["MORPHTARGETS_TANGENT"] = false;
  42565. defines["MORPHTARGETS_NORMAL"] = false;
  42566. defines["MORPHTARGETS"] = false;
  42567. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42568. }
  42569. }
  42570. return true;
  42571. };
  42572. /**
  42573. * Prepares the defines related to the light information passed in parameter
  42574. * @param scene The scene we are intending to draw
  42575. * @param mesh The mesh the effect is compiling for
  42576. * @param defines The defines to update
  42577. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42578. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42579. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42580. * @returns true if normals will be required for the rest of the effect
  42581. */
  42582. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42583. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42584. if (disableLighting === void 0) { disableLighting = false; }
  42585. if (!defines._areLightsDirty) {
  42586. return defines._needNormals;
  42587. }
  42588. var lightIndex = 0;
  42589. var needNormals = false;
  42590. var needRebuild = false;
  42591. var lightmapMode = false;
  42592. var shadowEnabled = false;
  42593. var specularEnabled = false;
  42594. if (scene.lightsEnabled && !disableLighting) {
  42595. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42596. var light = _a[_i];
  42597. needNormals = true;
  42598. if (defines["LIGHT" + lightIndex] === undefined) {
  42599. needRebuild = true;
  42600. }
  42601. defines["LIGHT" + lightIndex] = true;
  42602. defines["SPOTLIGHT" + lightIndex] = false;
  42603. defines["HEMILIGHT" + lightIndex] = false;
  42604. defines["POINTLIGHT" + lightIndex] = false;
  42605. defines["DIRLIGHT" + lightIndex] = false;
  42606. var type;
  42607. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42608. type = "SPOTLIGHT" + lightIndex;
  42609. var spotLight = light;
  42610. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42611. }
  42612. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42613. type = "HEMILIGHT" + lightIndex;
  42614. }
  42615. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42616. type = "POINTLIGHT" + lightIndex;
  42617. }
  42618. else {
  42619. type = "DIRLIGHT" + lightIndex;
  42620. }
  42621. defines[type] = true;
  42622. // Specular
  42623. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42624. specularEnabled = true;
  42625. }
  42626. // Shadows
  42627. defines["SHADOW" + lightIndex] = false;
  42628. defines["SHADOWPCF" + lightIndex] = false;
  42629. defines["SHADOWPCSS" + lightIndex] = false;
  42630. defines["SHADOWPOISSON" + lightIndex] = false;
  42631. defines["SHADOWESM" + lightIndex] = false;
  42632. defines["SHADOWCUBE" + lightIndex] = false;
  42633. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42634. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42635. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42636. var shadowGenerator = light.getShadowGenerator();
  42637. if (shadowGenerator) {
  42638. shadowEnabled = true;
  42639. shadowGenerator.prepareDefines(defines, lightIndex);
  42640. }
  42641. }
  42642. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42643. lightmapMode = true;
  42644. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42645. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42646. }
  42647. else {
  42648. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42649. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42650. }
  42651. lightIndex++;
  42652. if (lightIndex === maxSimultaneousLights)
  42653. break;
  42654. }
  42655. }
  42656. defines["SPECULARTERM"] = specularEnabled;
  42657. defines["SHADOWS"] = shadowEnabled;
  42658. // Resetting all other lights if any
  42659. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42660. if (defines["LIGHT" + index] !== undefined) {
  42661. defines["LIGHT" + index] = false;
  42662. defines["HEMILIGHT" + lightIndex] = false;
  42663. defines["POINTLIGHT" + lightIndex] = false;
  42664. defines["DIRLIGHT" + lightIndex] = false;
  42665. defines["SPOTLIGHT" + lightIndex] = false;
  42666. defines["SHADOW" + lightIndex] = false;
  42667. }
  42668. }
  42669. var caps = scene.getEngine().getCaps();
  42670. if (defines["SHADOWFLOAT"] === undefined) {
  42671. needRebuild = true;
  42672. }
  42673. defines["SHADOWFLOAT"] = shadowEnabled &&
  42674. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42675. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42676. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42677. if (needRebuild) {
  42678. defines.rebuild();
  42679. }
  42680. return needNormals;
  42681. };
  42682. /**
  42683. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42684. * that won t be acctive due to defines being turned off.
  42685. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42686. * @param samplersList The samplers list
  42687. * @param defines The defines helping in the list generation
  42688. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42689. */
  42690. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42691. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42692. var uniformsList;
  42693. var uniformBuffersList = null;
  42694. if (uniformsListOrOptions.uniformsNames) {
  42695. var options = uniformsListOrOptions;
  42696. uniformsList = options.uniformsNames;
  42697. uniformBuffersList = options.uniformBuffersNames;
  42698. samplersList = options.samplers;
  42699. defines = options.defines;
  42700. maxSimultaneousLights = options.maxSimultaneousLights;
  42701. }
  42702. else {
  42703. uniformsList = uniformsListOrOptions;
  42704. if (!samplersList) {
  42705. samplersList = [];
  42706. }
  42707. }
  42708. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42709. if (!defines["LIGHT" + lightIndex]) {
  42710. break;
  42711. }
  42712. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42713. if (uniformBuffersList) {
  42714. uniformBuffersList.push("Light" + lightIndex);
  42715. }
  42716. samplersList.push("shadowSampler" + lightIndex);
  42717. samplersList.push("depthSampler" + lightIndex);
  42718. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42719. samplersList.push("projectionLightSampler" + lightIndex);
  42720. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42721. }
  42722. }
  42723. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42724. uniformsList.push("morphTargetInfluences");
  42725. }
  42726. };
  42727. /**
  42728. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42729. * @param defines The defines to update while falling back
  42730. * @param fallbacks The authorized effect fallbacks
  42731. * @param maxSimultaneousLights The maximum number of lights allowed
  42732. * @param rank the current rank of the Effect
  42733. * @returns The newly affected rank
  42734. */
  42735. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42736. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42737. if (rank === void 0) { rank = 0; }
  42738. var lightFallbackRank = 0;
  42739. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42740. if (!defines["LIGHT" + lightIndex]) {
  42741. break;
  42742. }
  42743. if (lightIndex > 0) {
  42744. lightFallbackRank = rank + lightIndex;
  42745. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42746. }
  42747. if (!defines["SHADOWS"]) {
  42748. if (defines["SHADOW" + lightIndex]) {
  42749. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42750. }
  42751. if (defines["SHADOWPCF" + lightIndex]) {
  42752. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42753. }
  42754. if (defines["SHADOWPCSS" + lightIndex]) {
  42755. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42756. }
  42757. if (defines["SHADOWPOISSON" + lightIndex]) {
  42758. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42759. }
  42760. if (defines["SHADOWESM" + lightIndex]) {
  42761. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42762. }
  42763. }
  42764. }
  42765. return lightFallbackRank++;
  42766. };
  42767. /**
  42768. * Prepares the list of attributes required for morph targets according to the effect defines.
  42769. * @param attribs The current list of supported attribs
  42770. * @param mesh The mesh to prepare the morph targets attributes for
  42771. * @param defines The current Defines of the effect
  42772. */
  42773. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42774. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42775. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42776. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42777. var manager = mesh.morphTargetManager;
  42778. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42779. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42780. for (var index = 0; index < influencers; index++) {
  42781. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42782. if (normal) {
  42783. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42784. }
  42785. if (tangent) {
  42786. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42787. }
  42788. if (attribs.length > maxAttributesCount) {
  42789. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42790. }
  42791. }
  42792. }
  42793. };
  42794. /**
  42795. * Prepares the list of attributes required for bones according to the effect defines.
  42796. * @param attribs The current list of supported attribs
  42797. * @param mesh The mesh to prepare the bones attributes for
  42798. * @param defines The current Defines of the effect
  42799. * @param fallbacks The current efffect fallback strategy
  42800. */
  42801. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42802. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42803. fallbacks.addCPUSkinningFallback(0, mesh);
  42804. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42805. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42806. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42807. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42808. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42809. }
  42810. }
  42811. };
  42812. /**
  42813. * Prepares the list of attributes required for instances according to the effect defines.
  42814. * @param attribs The current list of supported attribs
  42815. * @param defines The current Defines of the effect
  42816. */
  42817. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42818. if (defines["INSTANCES"]) {
  42819. attribs.push("world0");
  42820. attribs.push("world1");
  42821. attribs.push("world2");
  42822. attribs.push("world3");
  42823. }
  42824. };
  42825. /**
  42826. * Binds the light shadow information to the effect for the given mesh.
  42827. * @param light The light containing the generator
  42828. * @param scene The scene the lights belongs to
  42829. * @param mesh The mesh we are binding the information to render
  42830. * @param lightIndex The light index in the effect used to render the mesh
  42831. * @param effect The effect we are binding the data to
  42832. */
  42833. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42834. if (light.shadowEnabled && mesh.receiveShadows) {
  42835. var shadowGenerator = light.getShadowGenerator();
  42836. if (shadowGenerator) {
  42837. shadowGenerator.bindShadowLight(lightIndex, effect);
  42838. }
  42839. }
  42840. };
  42841. /**
  42842. * Binds the light information to the effect.
  42843. * @param light The light containing the generator
  42844. * @param effect The effect we are binding the data to
  42845. * @param lightIndex The light index in the effect used to render
  42846. */
  42847. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42848. light.transferToEffect(effect, lightIndex + "");
  42849. };
  42850. /**
  42851. * Binds the lights information from the scene to the effect for the given mesh.
  42852. * @param scene The scene the lights belongs to
  42853. * @param mesh The mesh we are binding the information to render
  42854. * @param effect The effect we are binding the data to
  42855. * @param defines The generated defines for the effect
  42856. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42857. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42858. */
  42859. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42860. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42861. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42862. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42863. for (var i = 0; i < len; i++) {
  42864. var light = mesh._lightSources[i];
  42865. var iAsString = i.toString();
  42866. var scaledIntensity = light.getScaledIntensity();
  42867. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42868. MaterialHelper.BindLightProperties(light, effect, i);
  42869. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42870. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42871. if (defines["SPECULARTERM"]) {
  42872. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42873. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42874. }
  42875. // Shadows
  42876. if (scene.shadowsEnabled) {
  42877. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42878. }
  42879. light._uniformBuffer.update();
  42880. }
  42881. };
  42882. /**
  42883. * Binds the fog information from the scene to the effect for the given mesh.
  42884. * @param scene The scene the lights belongs to
  42885. * @param mesh The mesh we are binding the information to render
  42886. * @param effect The effect we are binding the data to
  42887. */
  42888. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42889. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42890. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42891. effect.setColor3("vFogColor", scene.fogColor);
  42892. }
  42893. };
  42894. /**
  42895. * Binds the bones information from the mesh to the effect.
  42896. * @param mesh The mesh we are binding the information to render
  42897. * @param effect The effect we are binding the data to
  42898. */
  42899. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42900. if (!effect || !mesh) {
  42901. return;
  42902. }
  42903. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42904. mesh.computeBonesUsingShaders = false;
  42905. }
  42906. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42907. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42908. if (matrices) {
  42909. effect.setMatrices("mBones", matrices);
  42910. }
  42911. }
  42912. };
  42913. /**
  42914. * Binds the morph targets information from the mesh to the effect.
  42915. * @param abstractMesh The mesh we are binding the information to render
  42916. * @param effect The effect we are binding the data to
  42917. */
  42918. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42919. var manager = abstractMesh.morphTargetManager;
  42920. if (!abstractMesh || !manager) {
  42921. return;
  42922. }
  42923. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42924. };
  42925. /**
  42926. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42927. * @param defines The generated defines used in the effect
  42928. * @param effect The effect we are binding the data to
  42929. * @param scene The scene we are willing to render with logarithmic scale for
  42930. */
  42931. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42932. if (defines["LOGARITHMICDEPTH"]) {
  42933. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42934. }
  42935. };
  42936. /**
  42937. * Binds the clip plane information from the scene to the effect.
  42938. * @param scene The scene the clip plane information are extracted from
  42939. * @param effect The effect we are binding the data to
  42940. */
  42941. MaterialHelper.BindClipPlane = function (effect, scene) {
  42942. if (scene.clipPlane) {
  42943. var clipPlane = scene.clipPlane;
  42944. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42945. }
  42946. };
  42947. return MaterialHelper;
  42948. }());
  42949. BABYLON.MaterialHelper = MaterialHelper;
  42950. })(BABYLON || (BABYLON = {}));
  42951. //# sourceMappingURL=babylon.materialHelper.js.map
  42952. var BABYLON;
  42953. (function (BABYLON) {
  42954. var PushMaterial = /** @class */ (function (_super) {
  42955. __extends(PushMaterial, _super);
  42956. function PushMaterial(name, scene) {
  42957. var _this = _super.call(this, name, scene) || this;
  42958. _this._normalMatrix = new BABYLON.Matrix();
  42959. _this.storeEffectOnSubMeshes = true;
  42960. return _this;
  42961. }
  42962. PushMaterial.prototype.getEffect = function () {
  42963. return this._activeEffect;
  42964. };
  42965. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42966. if (!mesh) {
  42967. return false;
  42968. }
  42969. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42970. return true;
  42971. }
  42972. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42973. };
  42974. /**
  42975. * Binds the given world matrix to the active effect
  42976. *
  42977. * @param world the matrix to bind
  42978. */
  42979. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42980. this._activeEffect.setMatrix("world", world);
  42981. };
  42982. /**
  42983. * Binds the given normal matrix to the active effect
  42984. *
  42985. * @param normalMatrix the matrix to bind
  42986. */
  42987. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42988. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42989. };
  42990. PushMaterial.prototype.bind = function (world, mesh) {
  42991. if (!mesh) {
  42992. return;
  42993. }
  42994. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42995. };
  42996. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42997. if (effect === void 0) { effect = null; }
  42998. _super.prototype._afterBind.call(this, mesh);
  42999. this.getScene()._cachedEffect = effect;
  43000. };
  43001. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43002. if (visibility === void 0) { visibility = 1; }
  43003. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43004. };
  43005. return PushMaterial;
  43006. }(BABYLON.Material));
  43007. BABYLON.PushMaterial = PushMaterial;
  43008. })(BABYLON || (BABYLON = {}));
  43009. //# sourceMappingURL=babylon.pushMaterial.js.map
  43010. var BABYLON;
  43011. (function (BABYLON) {
  43012. /** @hidden */
  43013. var StandardMaterialDefines = /** @class */ (function (_super) {
  43014. __extends(StandardMaterialDefines, _super);
  43015. function StandardMaterialDefines() {
  43016. var _this = _super.call(this) || this;
  43017. _this.MAINUV1 = false;
  43018. _this.MAINUV2 = false;
  43019. _this.DIFFUSE = false;
  43020. _this.DIFFUSEDIRECTUV = 0;
  43021. _this.AMBIENT = false;
  43022. _this.AMBIENTDIRECTUV = 0;
  43023. _this.OPACITY = false;
  43024. _this.OPACITYDIRECTUV = 0;
  43025. _this.OPACITYRGB = false;
  43026. _this.REFLECTION = false;
  43027. _this.EMISSIVE = false;
  43028. _this.EMISSIVEDIRECTUV = 0;
  43029. _this.SPECULAR = false;
  43030. _this.SPECULARDIRECTUV = 0;
  43031. _this.BUMP = false;
  43032. _this.BUMPDIRECTUV = 0;
  43033. _this.PARALLAX = false;
  43034. _this.PARALLAXOCCLUSION = false;
  43035. _this.SPECULAROVERALPHA = false;
  43036. _this.CLIPPLANE = false;
  43037. _this.ALPHATEST = false;
  43038. _this.DEPTHPREPASS = false;
  43039. _this.ALPHAFROMDIFFUSE = false;
  43040. _this.POINTSIZE = false;
  43041. _this.FOG = false;
  43042. _this.SPECULARTERM = false;
  43043. _this.DIFFUSEFRESNEL = false;
  43044. _this.OPACITYFRESNEL = false;
  43045. _this.REFLECTIONFRESNEL = false;
  43046. _this.REFRACTIONFRESNEL = false;
  43047. _this.EMISSIVEFRESNEL = false;
  43048. _this.FRESNEL = false;
  43049. _this.NORMAL = false;
  43050. _this.UV1 = false;
  43051. _this.UV2 = false;
  43052. _this.VERTEXCOLOR = false;
  43053. _this.VERTEXALPHA = false;
  43054. _this.NUM_BONE_INFLUENCERS = 0;
  43055. _this.BonesPerMesh = 0;
  43056. _this.INSTANCES = false;
  43057. _this.GLOSSINESS = false;
  43058. _this.ROUGHNESS = false;
  43059. _this.EMISSIVEASILLUMINATION = false;
  43060. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43061. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43062. _this.LIGHTMAP = false;
  43063. _this.LIGHTMAPDIRECTUV = 0;
  43064. _this.OBJECTSPACE_NORMALMAP = false;
  43065. _this.USELIGHTMAPASSHADOWMAP = false;
  43066. _this.REFLECTIONMAP_3D = false;
  43067. _this.REFLECTIONMAP_SPHERICAL = false;
  43068. _this.REFLECTIONMAP_PLANAR = false;
  43069. _this.REFLECTIONMAP_CUBIC = false;
  43070. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43071. _this.REFLECTIONMAP_PROJECTION = false;
  43072. _this.REFLECTIONMAP_SKYBOX = false;
  43073. _this.REFLECTIONMAP_EXPLICIT = false;
  43074. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43075. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43076. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43077. _this.INVERTCUBICMAP = false;
  43078. _this.LOGARITHMICDEPTH = false;
  43079. _this.REFRACTION = false;
  43080. _this.REFRACTIONMAP_3D = false;
  43081. _this.REFLECTIONOVERALPHA = false;
  43082. _this.TWOSIDEDLIGHTING = false;
  43083. _this.SHADOWFLOAT = false;
  43084. _this.MORPHTARGETS = false;
  43085. _this.MORPHTARGETS_NORMAL = false;
  43086. _this.MORPHTARGETS_TANGENT = false;
  43087. _this.NUM_MORPH_INFLUENCERS = 0;
  43088. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43089. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43090. _this.IMAGEPROCESSING = false;
  43091. _this.VIGNETTE = false;
  43092. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43093. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43094. _this.TONEMAPPING = false;
  43095. _this.CONTRAST = false;
  43096. _this.COLORCURVES = false;
  43097. _this.COLORGRADING = false;
  43098. _this.COLORGRADING3D = false;
  43099. _this.SAMPLER3DGREENDEPTH = false;
  43100. _this.SAMPLER3DBGRMAP = false;
  43101. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43102. /**
  43103. * If the reflection texture on this material is in linear color space
  43104. * @hidden
  43105. */
  43106. _this.IS_REFLECTION_LINEAR = false;
  43107. /**
  43108. * If the refraction texture on this material is in linear color space
  43109. * @hidden
  43110. */
  43111. _this.IS_REFRACTION_LINEAR = false;
  43112. _this.EXPOSURE = false;
  43113. _this.rebuild();
  43114. return _this;
  43115. }
  43116. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43117. var modes = [
  43118. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43119. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43120. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43121. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43122. ];
  43123. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43124. var mode = modes_1[_i];
  43125. this[mode] = (mode === modeToEnable);
  43126. }
  43127. };
  43128. return StandardMaterialDefines;
  43129. }(BABYLON.MaterialDefines));
  43130. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43131. var StandardMaterial = /** @class */ (function (_super) {
  43132. __extends(StandardMaterial, _super);
  43133. function StandardMaterial(name, scene) {
  43134. var _this = _super.call(this, name, scene) || this;
  43135. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43136. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43137. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43138. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43139. _this.specularPower = 64;
  43140. _this._useAlphaFromDiffuseTexture = false;
  43141. _this._useEmissiveAsIllumination = false;
  43142. _this._linkEmissiveWithDiffuse = false;
  43143. _this._useSpecularOverAlpha = false;
  43144. _this._useReflectionOverAlpha = false;
  43145. _this._disableLighting = false;
  43146. _this._useObjectSpaceNormalMap = false;
  43147. _this._useParallax = false;
  43148. _this._useParallaxOcclusion = false;
  43149. _this.parallaxScaleBias = 0.05;
  43150. _this._roughness = 0;
  43151. _this.indexOfRefraction = 0.98;
  43152. _this.invertRefractionY = true;
  43153. /**
  43154. * Defines the alpha limits in alpha test mode
  43155. */
  43156. _this.alphaCutOff = 0.4;
  43157. _this._useLightmapAsShadowmap = false;
  43158. _this._useReflectionFresnelFromSpecular = false;
  43159. _this._useGlossinessFromSpecularMapAlpha = false;
  43160. _this._maxSimultaneousLights = 4;
  43161. /**
  43162. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43163. */
  43164. _this._invertNormalMapX = false;
  43165. /**
  43166. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43167. */
  43168. _this._invertNormalMapY = false;
  43169. /**
  43170. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43171. */
  43172. _this._twoSidedLighting = false;
  43173. _this._renderTargets = new BABYLON.SmartArray(16);
  43174. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43175. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43176. // Setup the default processing configuration to the scene.
  43177. _this._attachImageProcessingConfiguration(null);
  43178. _this.getRenderTargetTextures = function () {
  43179. _this._renderTargets.reset();
  43180. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43181. _this._renderTargets.push(_this._reflectionTexture);
  43182. }
  43183. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43184. _this._renderTargets.push(_this._refractionTexture);
  43185. }
  43186. return _this._renderTargets;
  43187. };
  43188. return _this;
  43189. }
  43190. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43191. /**
  43192. * Gets the image processing configuration used either in this material.
  43193. */
  43194. get: function () {
  43195. return this._imageProcessingConfiguration;
  43196. },
  43197. /**
  43198. * Sets the Default image processing configuration used either in the this material.
  43199. *
  43200. * If sets to null, the scene one is in use.
  43201. */
  43202. set: function (value) {
  43203. this._attachImageProcessingConfiguration(value);
  43204. // Ensure the effect will be rebuilt.
  43205. this._markAllSubMeshesAsTexturesDirty();
  43206. },
  43207. enumerable: true,
  43208. configurable: true
  43209. });
  43210. /**
  43211. * Attaches a new image processing configuration to the Standard Material.
  43212. * @param configuration
  43213. */
  43214. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43215. var _this = this;
  43216. if (configuration === this._imageProcessingConfiguration) {
  43217. return;
  43218. }
  43219. // Detaches observer.
  43220. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43221. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43222. }
  43223. // Pick the scene configuration if needed.
  43224. if (!configuration) {
  43225. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43226. }
  43227. else {
  43228. this._imageProcessingConfiguration = configuration;
  43229. }
  43230. // Attaches observer.
  43231. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43232. _this._markAllSubMeshesAsImageProcessingDirty();
  43233. });
  43234. };
  43235. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43236. /**
  43237. * Gets wether the color curves effect is enabled.
  43238. */
  43239. get: function () {
  43240. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43241. },
  43242. /**
  43243. * Sets wether the color curves effect is enabled.
  43244. */
  43245. set: function (value) {
  43246. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43247. },
  43248. enumerable: true,
  43249. configurable: true
  43250. });
  43251. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43252. /**
  43253. * Gets wether the color grading effect is enabled.
  43254. */
  43255. get: function () {
  43256. return this.imageProcessingConfiguration.colorGradingEnabled;
  43257. },
  43258. /**
  43259. * Gets wether the color grading effect is enabled.
  43260. */
  43261. set: function (value) {
  43262. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43263. },
  43264. enumerable: true,
  43265. configurable: true
  43266. });
  43267. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43268. /**
  43269. * Gets wether tonemapping is enabled or not.
  43270. */
  43271. get: function () {
  43272. return this._imageProcessingConfiguration.toneMappingEnabled;
  43273. },
  43274. /**
  43275. * Sets wether tonemapping is enabled or not
  43276. */
  43277. set: function (value) {
  43278. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43279. },
  43280. enumerable: true,
  43281. configurable: true
  43282. });
  43283. ;
  43284. ;
  43285. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43286. /**
  43287. * The camera exposure used on this material.
  43288. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43289. * This corresponds to a photographic exposure.
  43290. */
  43291. get: function () {
  43292. return this._imageProcessingConfiguration.exposure;
  43293. },
  43294. /**
  43295. * The camera exposure used on this material.
  43296. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43297. * This corresponds to a photographic exposure.
  43298. */
  43299. set: function (value) {
  43300. this._imageProcessingConfiguration.exposure = value;
  43301. },
  43302. enumerable: true,
  43303. configurable: true
  43304. });
  43305. ;
  43306. ;
  43307. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43308. /**
  43309. * Gets The camera contrast used on this material.
  43310. */
  43311. get: function () {
  43312. return this._imageProcessingConfiguration.contrast;
  43313. },
  43314. /**
  43315. * Sets The camera contrast used on this material.
  43316. */
  43317. set: function (value) {
  43318. this._imageProcessingConfiguration.contrast = value;
  43319. },
  43320. enumerable: true,
  43321. configurable: true
  43322. });
  43323. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43324. /**
  43325. * Gets the Color Grading 2D Lookup Texture.
  43326. */
  43327. get: function () {
  43328. return this._imageProcessingConfiguration.colorGradingTexture;
  43329. },
  43330. /**
  43331. * Sets the Color Grading 2D Lookup Texture.
  43332. */
  43333. set: function (value) {
  43334. this._imageProcessingConfiguration.colorGradingTexture = value;
  43335. },
  43336. enumerable: true,
  43337. configurable: true
  43338. });
  43339. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43340. /**
  43341. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43342. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43343. * 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;
  43344. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43345. */
  43346. get: function () {
  43347. return this._imageProcessingConfiguration.colorCurves;
  43348. },
  43349. /**
  43350. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43351. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43352. * 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;
  43353. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43354. */
  43355. set: function (value) {
  43356. this._imageProcessingConfiguration.colorCurves = value;
  43357. },
  43358. enumerable: true,
  43359. configurable: true
  43360. });
  43361. StandardMaterial.prototype.getClassName = function () {
  43362. return "StandardMaterial";
  43363. };
  43364. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43365. get: function () {
  43366. return this._useLogarithmicDepth;
  43367. },
  43368. set: function (value) {
  43369. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43370. this._markAllSubMeshesAsMiscDirty();
  43371. },
  43372. enumerable: true,
  43373. configurable: true
  43374. });
  43375. StandardMaterial.prototype.needAlphaBlending = function () {
  43376. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43377. };
  43378. StandardMaterial.prototype.needAlphaTesting = function () {
  43379. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43380. };
  43381. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43382. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43383. };
  43384. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43385. return this._diffuseTexture;
  43386. };
  43387. /**
  43388. * Child classes can use it to update shaders
  43389. */
  43390. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43391. if (useInstances === void 0) { useInstances = false; }
  43392. if (subMesh.effect && this.isFrozen) {
  43393. if (this._wasPreviouslyReady && subMesh.effect) {
  43394. return true;
  43395. }
  43396. }
  43397. if (!subMesh._materialDefines) {
  43398. subMesh._materialDefines = new StandardMaterialDefines();
  43399. }
  43400. var scene = this.getScene();
  43401. var defines = subMesh._materialDefines;
  43402. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43403. if (defines._renderId === scene.getRenderId()) {
  43404. return true;
  43405. }
  43406. }
  43407. var engine = scene.getEngine();
  43408. // Lights
  43409. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43410. // Textures
  43411. if (defines._areTexturesDirty) {
  43412. defines._needUVs = false;
  43413. defines.MAINUV1 = false;
  43414. defines.MAINUV2 = false;
  43415. if (scene.texturesEnabled) {
  43416. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43417. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43418. return false;
  43419. }
  43420. else {
  43421. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43422. }
  43423. }
  43424. else {
  43425. defines.DIFFUSE = false;
  43426. }
  43427. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43428. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43429. return false;
  43430. }
  43431. else {
  43432. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43433. }
  43434. }
  43435. else {
  43436. defines.AMBIENT = false;
  43437. }
  43438. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43439. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43440. return false;
  43441. }
  43442. else {
  43443. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43444. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43445. }
  43446. }
  43447. else {
  43448. defines.OPACITY = false;
  43449. }
  43450. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43451. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43452. return false;
  43453. }
  43454. else {
  43455. defines._needNormals = true;
  43456. defines.REFLECTION = true;
  43457. defines.ROUGHNESS = (this._roughness > 0);
  43458. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43459. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43460. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43461. switch (this._reflectionTexture.coordinatesMode) {
  43462. case BABYLON.Texture.EXPLICIT_MODE:
  43463. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43464. break;
  43465. case BABYLON.Texture.PLANAR_MODE:
  43466. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43467. break;
  43468. case BABYLON.Texture.PROJECTION_MODE:
  43469. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43470. break;
  43471. case BABYLON.Texture.SKYBOX_MODE:
  43472. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43473. break;
  43474. case BABYLON.Texture.SPHERICAL_MODE:
  43475. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43476. break;
  43477. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43478. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43479. break;
  43480. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43481. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43482. break;
  43483. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43484. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43485. break;
  43486. case BABYLON.Texture.CUBIC_MODE:
  43487. case BABYLON.Texture.INVCUBIC_MODE:
  43488. default:
  43489. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43490. break;
  43491. }
  43492. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43493. }
  43494. }
  43495. else {
  43496. defines.REFLECTION = false;
  43497. }
  43498. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43499. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43500. return false;
  43501. }
  43502. else {
  43503. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43504. }
  43505. }
  43506. else {
  43507. defines.EMISSIVE = false;
  43508. }
  43509. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43510. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43511. return false;
  43512. }
  43513. else {
  43514. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43515. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43516. }
  43517. }
  43518. else {
  43519. defines.LIGHTMAP = false;
  43520. }
  43521. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43522. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43523. return false;
  43524. }
  43525. else {
  43526. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43527. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43528. }
  43529. }
  43530. else {
  43531. defines.SPECULAR = false;
  43532. }
  43533. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43534. // Bump texure can not be not blocking.
  43535. if (!this._bumpTexture.isReady()) {
  43536. return false;
  43537. }
  43538. else {
  43539. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43540. defines.PARALLAX = this._useParallax;
  43541. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43542. }
  43543. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43544. }
  43545. else {
  43546. defines.BUMP = false;
  43547. }
  43548. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43549. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43550. return false;
  43551. }
  43552. else {
  43553. defines._needUVs = true;
  43554. defines.REFRACTION = true;
  43555. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43556. }
  43557. }
  43558. else {
  43559. defines.REFRACTION = false;
  43560. }
  43561. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43562. }
  43563. else {
  43564. defines.DIFFUSE = false;
  43565. defines.AMBIENT = false;
  43566. defines.OPACITY = false;
  43567. defines.REFLECTION = false;
  43568. defines.EMISSIVE = false;
  43569. defines.LIGHTMAP = false;
  43570. defines.BUMP = false;
  43571. defines.REFRACTION = false;
  43572. }
  43573. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43574. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43575. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43576. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43577. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43578. }
  43579. if (defines._areImageProcessingDirty) {
  43580. if (!this._imageProcessingConfiguration.isReady()) {
  43581. return false;
  43582. }
  43583. this._imageProcessingConfiguration.prepareDefines(defines);
  43584. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43585. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43586. }
  43587. if (defines._areFresnelDirty) {
  43588. if (StandardMaterial.FresnelEnabled) {
  43589. // Fresnel
  43590. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43591. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43592. this._reflectionFresnelParameters) {
  43593. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43594. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43595. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43596. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43597. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43598. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43599. defines._needNormals = true;
  43600. defines.FRESNEL = true;
  43601. }
  43602. }
  43603. else {
  43604. defines.FRESNEL = false;
  43605. }
  43606. }
  43607. // Misc.
  43608. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43609. // Attribs
  43610. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43611. // Values that need to be evaluated on every frame
  43612. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43613. // Get correct effect
  43614. if (defines.isDirty) {
  43615. defines.markAsProcessed();
  43616. scene.resetCachedMaterial();
  43617. // Fallbacks
  43618. var fallbacks = new BABYLON.EffectFallbacks();
  43619. if (defines.REFLECTION) {
  43620. fallbacks.addFallback(0, "REFLECTION");
  43621. }
  43622. if (defines.SPECULAR) {
  43623. fallbacks.addFallback(0, "SPECULAR");
  43624. }
  43625. if (defines.BUMP) {
  43626. fallbacks.addFallback(0, "BUMP");
  43627. }
  43628. if (defines.PARALLAX) {
  43629. fallbacks.addFallback(1, "PARALLAX");
  43630. }
  43631. if (defines.PARALLAXOCCLUSION) {
  43632. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43633. }
  43634. if (defines.SPECULAROVERALPHA) {
  43635. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43636. }
  43637. if (defines.FOG) {
  43638. fallbacks.addFallback(1, "FOG");
  43639. }
  43640. if (defines.POINTSIZE) {
  43641. fallbacks.addFallback(0, "POINTSIZE");
  43642. }
  43643. if (defines.LOGARITHMICDEPTH) {
  43644. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43645. }
  43646. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43647. if (defines.SPECULARTERM) {
  43648. fallbacks.addFallback(0, "SPECULARTERM");
  43649. }
  43650. if (defines.DIFFUSEFRESNEL) {
  43651. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43652. }
  43653. if (defines.OPACITYFRESNEL) {
  43654. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43655. }
  43656. if (defines.REFLECTIONFRESNEL) {
  43657. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43658. }
  43659. if (defines.EMISSIVEFRESNEL) {
  43660. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43661. }
  43662. if (defines.FRESNEL) {
  43663. fallbacks.addFallback(4, "FRESNEL");
  43664. }
  43665. //Attributes
  43666. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43667. if (defines.NORMAL) {
  43668. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43669. }
  43670. if (defines.UV1) {
  43671. attribs.push(BABYLON.VertexBuffer.UVKind);
  43672. }
  43673. if (defines.UV2) {
  43674. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43675. }
  43676. if (defines.VERTEXCOLOR) {
  43677. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43678. }
  43679. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43680. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43681. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43682. var shaderName = "default";
  43683. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43684. "vFogInfos", "vFogColor", "pointSize",
  43685. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43686. "mBones",
  43687. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43688. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43689. "vReflectionPosition", "vReflectionSize",
  43690. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43691. ];
  43692. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43693. var uniformBuffers = ["Material", "Scene"];
  43694. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43695. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43696. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43697. uniformsNames: uniforms,
  43698. uniformBuffersNames: uniformBuffers,
  43699. samplers: samplers,
  43700. defines: defines,
  43701. maxSimultaneousLights: this._maxSimultaneousLights
  43702. });
  43703. if (this.customShaderNameResolve) {
  43704. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43705. }
  43706. var join = defines.toString();
  43707. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43708. attributes: attribs,
  43709. uniformsNames: uniforms,
  43710. uniformBuffersNames: uniformBuffers,
  43711. samplers: samplers,
  43712. defines: join,
  43713. fallbacks: fallbacks,
  43714. onCompiled: this.onCompiled,
  43715. onError: this.onError,
  43716. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43717. }, engine), defines);
  43718. this.buildUniformLayout();
  43719. }
  43720. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43721. return false;
  43722. }
  43723. defines._renderId = scene.getRenderId();
  43724. this._wasPreviouslyReady = true;
  43725. return true;
  43726. };
  43727. StandardMaterial.prototype.buildUniformLayout = function () {
  43728. // Order is important !
  43729. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43730. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43731. this._uniformBuffer.addUniform("opacityParts", 4);
  43732. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43733. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43734. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43735. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43736. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43737. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43738. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43739. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43740. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43741. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43742. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43743. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43744. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43745. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43746. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43747. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43748. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43749. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43750. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43751. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43752. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43753. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43754. this._uniformBuffer.addUniform("specularMatrix", 16);
  43755. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43756. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43757. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43758. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43759. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43760. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43761. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43762. this._uniformBuffer.addUniform("pointSize", 1);
  43763. this._uniformBuffer.create();
  43764. };
  43765. StandardMaterial.prototype.unbind = function () {
  43766. if (this._activeEffect) {
  43767. var needFlag = false;
  43768. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43769. this._activeEffect.setTexture("reflection2DSampler", null);
  43770. needFlag = true;
  43771. }
  43772. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43773. this._activeEffect.setTexture("refraction2DSampler", null);
  43774. needFlag = true;
  43775. }
  43776. if (needFlag) {
  43777. this._markAllSubMeshesAsTexturesDirty();
  43778. }
  43779. }
  43780. _super.prototype.unbind.call(this);
  43781. };
  43782. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43783. var scene = this.getScene();
  43784. var defines = subMesh._materialDefines;
  43785. if (!defines) {
  43786. return;
  43787. }
  43788. var effect = subMesh.effect;
  43789. if (!effect) {
  43790. return;
  43791. }
  43792. this._activeEffect = effect;
  43793. // Matrices
  43794. this.bindOnlyWorldMatrix(world);
  43795. // Normal Matrix
  43796. if (defines.OBJECTSPACE_NORMALMAP) {
  43797. world.toNormalMatrix(this._normalMatrix);
  43798. this.bindOnlyNormalMatrix(this._normalMatrix);
  43799. }
  43800. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43801. // Bones
  43802. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43803. if (mustRebind) {
  43804. this._uniformBuffer.bindToEffect(effect, "Material");
  43805. this.bindViewProjection(effect);
  43806. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43807. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43808. // Fresnel
  43809. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43810. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43811. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43812. }
  43813. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43814. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43815. }
  43816. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43817. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43818. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43819. }
  43820. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43821. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43822. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43823. }
  43824. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43825. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43826. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43827. }
  43828. }
  43829. // Textures
  43830. if (scene.texturesEnabled) {
  43831. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43832. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43833. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43834. if (this._diffuseTexture.hasAlpha) {
  43835. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43836. }
  43837. }
  43838. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43839. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43840. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43841. }
  43842. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43843. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43844. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43845. }
  43846. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43847. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43848. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43849. if (this._reflectionTexture.boundingBoxSize) {
  43850. var cubeTexture = this._reflectionTexture;
  43851. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43852. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43853. }
  43854. }
  43855. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43856. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43857. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43858. }
  43859. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43860. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43861. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43862. }
  43863. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43864. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43865. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43866. }
  43867. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43868. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43869. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43870. if (scene._mirroredCameraPosition) {
  43871. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43872. }
  43873. else {
  43874. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43875. }
  43876. }
  43877. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43878. var depth = 1.0;
  43879. if (!this._refractionTexture.isCube) {
  43880. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43881. if (this._refractionTexture.depth) {
  43882. depth = this._refractionTexture.depth;
  43883. }
  43884. }
  43885. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43886. }
  43887. }
  43888. // Point size
  43889. if (this.pointsCloud) {
  43890. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43891. }
  43892. if (defines.SPECULARTERM) {
  43893. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43894. }
  43895. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43896. // Diffuse
  43897. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43898. }
  43899. // Textures
  43900. if (scene.texturesEnabled) {
  43901. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43902. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43903. }
  43904. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43905. effect.setTexture("ambientSampler", this._ambientTexture);
  43906. }
  43907. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43908. effect.setTexture("opacitySampler", this._opacityTexture);
  43909. }
  43910. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43911. if (this._reflectionTexture.isCube) {
  43912. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43913. }
  43914. else {
  43915. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43916. }
  43917. }
  43918. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43919. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43920. }
  43921. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43922. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43923. }
  43924. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43925. effect.setTexture("specularSampler", this._specularTexture);
  43926. }
  43927. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43928. effect.setTexture("bumpSampler", this._bumpTexture);
  43929. }
  43930. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43931. var depth = 1.0;
  43932. if (this._refractionTexture.isCube) {
  43933. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43934. }
  43935. else {
  43936. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43937. }
  43938. }
  43939. }
  43940. // Clip plane
  43941. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43942. // Colors
  43943. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43944. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43945. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43946. }
  43947. if (mustRebind || !this.isFrozen) {
  43948. // Lights
  43949. if (scene.lightsEnabled && !this._disableLighting) {
  43950. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43951. }
  43952. // View
  43953. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43954. this.bindView(effect);
  43955. }
  43956. // Fog
  43957. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43958. // Morph targets
  43959. if (defines.NUM_MORPH_INFLUENCERS) {
  43960. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43961. }
  43962. // Log. depth
  43963. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43964. // image processing
  43965. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43966. this._imageProcessingConfiguration.bind(this._activeEffect);
  43967. }
  43968. }
  43969. this._uniformBuffer.update();
  43970. this._afterBind(mesh, this._activeEffect);
  43971. };
  43972. StandardMaterial.prototype.getAnimatables = function () {
  43973. var results = [];
  43974. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43975. results.push(this._diffuseTexture);
  43976. }
  43977. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43978. results.push(this._ambientTexture);
  43979. }
  43980. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43981. results.push(this._opacityTexture);
  43982. }
  43983. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43984. results.push(this._reflectionTexture);
  43985. }
  43986. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43987. results.push(this._emissiveTexture);
  43988. }
  43989. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43990. results.push(this._specularTexture);
  43991. }
  43992. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43993. results.push(this._bumpTexture);
  43994. }
  43995. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43996. results.push(this._lightmapTexture);
  43997. }
  43998. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43999. results.push(this._refractionTexture);
  44000. }
  44001. return results;
  44002. };
  44003. StandardMaterial.prototype.getActiveTextures = function () {
  44004. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44005. if (this._diffuseTexture) {
  44006. activeTextures.push(this._diffuseTexture);
  44007. }
  44008. if (this._ambientTexture) {
  44009. activeTextures.push(this._ambientTexture);
  44010. }
  44011. if (this._opacityTexture) {
  44012. activeTextures.push(this._opacityTexture);
  44013. }
  44014. if (this._reflectionTexture) {
  44015. activeTextures.push(this._reflectionTexture);
  44016. }
  44017. if (this._emissiveTexture) {
  44018. activeTextures.push(this._emissiveTexture);
  44019. }
  44020. if (this._specularTexture) {
  44021. activeTextures.push(this._specularTexture);
  44022. }
  44023. if (this._bumpTexture) {
  44024. activeTextures.push(this._bumpTexture);
  44025. }
  44026. if (this._lightmapTexture) {
  44027. activeTextures.push(this._lightmapTexture);
  44028. }
  44029. if (this._refractionTexture) {
  44030. activeTextures.push(this._refractionTexture);
  44031. }
  44032. return activeTextures;
  44033. };
  44034. StandardMaterial.prototype.hasTexture = function (texture) {
  44035. if (_super.prototype.hasTexture.call(this, texture)) {
  44036. return true;
  44037. }
  44038. if (this._diffuseTexture === texture) {
  44039. return true;
  44040. }
  44041. if (this._ambientTexture === texture) {
  44042. return true;
  44043. }
  44044. if (this._opacityTexture === texture) {
  44045. return true;
  44046. }
  44047. if (this._reflectionTexture === texture) {
  44048. return true;
  44049. }
  44050. if (this._emissiveTexture === texture) {
  44051. return true;
  44052. }
  44053. if (this._specularTexture === texture) {
  44054. return true;
  44055. }
  44056. if (this._bumpTexture === texture) {
  44057. return true;
  44058. }
  44059. if (this._lightmapTexture === texture) {
  44060. return true;
  44061. }
  44062. if (this._refractionTexture === texture) {
  44063. return true;
  44064. }
  44065. return false;
  44066. };
  44067. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44068. if (forceDisposeTextures) {
  44069. if (this._diffuseTexture) {
  44070. this._diffuseTexture.dispose();
  44071. }
  44072. if (this._ambientTexture) {
  44073. this._ambientTexture.dispose();
  44074. }
  44075. if (this._opacityTexture) {
  44076. this._opacityTexture.dispose();
  44077. }
  44078. if (this._reflectionTexture) {
  44079. this._reflectionTexture.dispose();
  44080. }
  44081. if (this._emissiveTexture) {
  44082. this._emissiveTexture.dispose();
  44083. }
  44084. if (this._specularTexture) {
  44085. this._specularTexture.dispose();
  44086. }
  44087. if (this._bumpTexture) {
  44088. this._bumpTexture.dispose();
  44089. }
  44090. if (this._lightmapTexture) {
  44091. this._lightmapTexture.dispose();
  44092. }
  44093. if (this._refractionTexture) {
  44094. this._refractionTexture.dispose();
  44095. }
  44096. }
  44097. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44098. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44099. }
  44100. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44101. };
  44102. StandardMaterial.prototype.clone = function (name) {
  44103. var _this = this;
  44104. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44105. result.name = name;
  44106. result.id = name;
  44107. return result;
  44108. };
  44109. StandardMaterial.prototype.serialize = function () {
  44110. return BABYLON.SerializationHelper.Serialize(this);
  44111. };
  44112. // Statics
  44113. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44114. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44115. };
  44116. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44117. get: function () {
  44118. return StandardMaterial._DiffuseTextureEnabled;
  44119. },
  44120. set: function (value) {
  44121. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44122. return;
  44123. }
  44124. StandardMaterial._DiffuseTextureEnabled = value;
  44125. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44126. },
  44127. enumerable: true,
  44128. configurable: true
  44129. });
  44130. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44131. get: function () {
  44132. return StandardMaterial._AmbientTextureEnabled;
  44133. },
  44134. set: function (value) {
  44135. if (StandardMaterial._AmbientTextureEnabled === value) {
  44136. return;
  44137. }
  44138. StandardMaterial._AmbientTextureEnabled = value;
  44139. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44140. },
  44141. enumerable: true,
  44142. configurable: true
  44143. });
  44144. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44145. get: function () {
  44146. return StandardMaterial._OpacityTextureEnabled;
  44147. },
  44148. set: function (value) {
  44149. if (StandardMaterial._OpacityTextureEnabled === value) {
  44150. return;
  44151. }
  44152. StandardMaterial._OpacityTextureEnabled = value;
  44153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44154. },
  44155. enumerable: true,
  44156. configurable: true
  44157. });
  44158. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44159. get: function () {
  44160. return StandardMaterial._ReflectionTextureEnabled;
  44161. },
  44162. set: function (value) {
  44163. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44164. return;
  44165. }
  44166. StandardMaterial._ReflectionTextureEnabled = value;
  44167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44168. },
  44169. enumerable: true,
  44170. configurable: true
  44171. });
  44172. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44173. get: function () {
  44174. return StandardMaterial._EmissiveTextureEnabled;
  44175. },
  44176. set: function (value) {
  44177. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44178. return;
  44179. }
  44180. StandardMaterial._EmissiveTextureEnabled = value;
  44181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44182. },
  44183. enumerable: true,
  44184. configurable: true
  44185. });
  44186. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44187. get: function () {
  44188. return StandardMaterial._SpecularTextureEnabled;
  44189. },
  44190. set: function (value) {
  44191. if (StandardMaterial._SpecularTextureEnabled === value) {
  44192. return;
  44193. }
  44194. StandardMaterial._SpecularTextureEnabled = value;
  44195. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44196. },
  44197. enumerable: true,
  44198. configurable: true
  44199. });
  44200. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44201. get: function () {
  44202. return StandardMaterial._BumpTextureEnabled;
  44203. },
  44204. set: function (value) {
  44205. if (StandardMaterial._BumpTextureEnabled === value) {
  44206. return;
  44207. }
  44208. StandardMaterial._BumpTextureEnabled = value;
  44209. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44210. },
  44211. enumerable: true,
  44212. configurable: true
  44213. });
  44214. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44215. get: function () {
  44216. return StandardMaterial._LightmapTextureEnabled;
  44217. },
  44218. set: function (value) {
  44219. if (StandardMaterial._LightmapTextureEnabled === value) {
  44220. return;
  44221. }
  44222. StandardMaterial._LightmapTextureEnabled = value;
  44223. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44224. },
  44225. enumerable: true,
  44226. configurable: true
  44227. });
  44228. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44229. get: function () {
  44230. return StandardMaterial._RefractionTextureEnabled;
  44231. },
  44232. set: function (value) {
  44233. if (StandardMaterial._RefractionTextureEnabled === value) {
  44234. return;
  44235. }
  44236. StandardMaterial._RefractionTextureEnabled = value;
  44237. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44238. },
  44239. enumerable: true,
  44240. configurable: true
  44241. });
  44242. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44243. get: function () {
  44244. return StandardMaterial._ColorGradingTextureEnabled;
  44245. },
  44246. set: function (value) {
  44247. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44248. return;
  44249. }
  44250. StandardMaterial._ColorGradingTextureEnabled = value;
  44251. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44252. },
  44253. enumerable: true,
  44254. configurable: true
  44255. });
  44256. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44257. get: function () {
  44258. return StandardMaterial._FresnelEnabled;
  44259. },
  44260. set: function (value) {
  44261. if (StandardMaterial._FresnelEnabled === value) {
  44262. return;
  44263. }
  44264. StandardMaterial._FresnelEnabled = value;
  44265. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44266. },
  44267. enumerable: true,
  44268. configurable: true
  44269. });
  44270. // Flags used to enable or disable a type of texture for all Standard Materials
  44271. StandardMaterial._DiffuseTextureEnabled = true;
  44272. StandardMaterial._AmbientTextureEnabled = true;
  44273. StandardMaterial._OpacityTextureEnabled = true;
  44274. StandardMaterial._ReflectionTextureEnabled = true;
  44275. StandardMaterial._EmissiveTextureEnabled = true;
  44276. StandardMaterial._SpecularTextureEnabled = true;
  44277. StandardMaterial._BumpTextureEnabled = true;
  44278. StandardMaterial._LightmapTextureEnabled = true;
  44279. StandardMaterial._RefractionTextureEnabled = true;
  44280. StandardMaterial._ColorGradingTextureEnabled = true;
  44281. StandardMaterial._FresnelEnabled = true;
  44282. __decorate([
  44283. BABYLON.serializeAsTexture("diffuseTexture")
  44284. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44285. __decorate([
  44286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44287. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44288. __decorate([
  44289. BABYLON.serializeAsTexture("ambientTexture")
  44290. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44291. __decorate([
  44292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44293. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44294. __decorate([
  44295. BABYLON.serializeAsTexture("opacityTexture")
  44296. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44297. __decorate([
  44298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44299. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44300. __decorate([
  44301. BABYLON.serializeAsTexture("reflectionTexture")
  44302. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44303. __decorate([
  44304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44305. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44306. __decorate([
  44307. BABYLON.serializeAsTexture("emissiveTexture")
  44308. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44309. __decorate([
  44310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44311. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44312. __decorate([
  44313. BABYLON.serializeAsTexture("specularTexture")
  44314. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44315. __decorate([
  44316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44317. ], StandardMaterial.prototype, "specularTexture", void 0);
  44318. __decorate([
  44319. BABYLON.serializeAsTexture("bumpTexture")
  44320. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44321. __decorate([
  44322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44323. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44324. __decorate([
  44325. BABYLON.serializeAsTexture("lightmapTexture")
  44326. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44327. __decorate([
  44328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44329. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44330. __decorate([
  44331. BABYLON.serializeAsTexture("refractionTexture")
  44332. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44333. __decorate([
  44334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44335. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44336. __decorate([
  44337. BABYLON.serializeAsColor3("ambient")
  44338. ], StandardMaterial.prototype, "ambientColor", void 0);
  44339. __decorate([
  44340. BABYLON.serializeAsColor3("diffuse")
  44341. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44342. __decorate([
  44343. BABYLON.serializeAsColor3("specular")
  44344. ], StandardMaterial.prototype, "specularColor", void 0);
  44345. __decorate([
  44346. BABYLON.serializeAsColor3("emissive")
  44347. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44348. __decorate([
  44349. BABYLON.serialize()
  44350. ], StandardMaterial.prototype, "specularPower", void 0);
  44351. __decorate([
  44352. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44353. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44354. __decorate([
  44355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44356. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44357. __decorate([
  44358. BABYLON.serialize("useEmissiveAsIllumination")
  44359. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44360. __decorate([
  44361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44362. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44363. __decorate([
  44364. BABYLON.serialize("linkEmissiveWithDiffuse")
  44365. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44366. __decorate([
  44367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44368. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44369. __decorate([
  44370. BABYLON.serialize("useSpecularOverAlpha")
  44371. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44372. __decorate([
  44373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44374. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44375. __decorate([
  44376. BABYLON.serialize("useReflectionOverAlpha")
  44377. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44378. __decorate([
  44379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44380. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44381. __decorate([
  44382. BABYLON.serialize("disableLighting")
  44383. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44384. __decorate([
  44385. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44386. ], StandardMaterial.prototype, "disableLighting", void 0);
  44387. __decorate([
  44388. BABYLON.serialize("useObjectSpaceNormalMap")
  44389. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44390. __decorate([
  44391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44392. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44393. __decorate([
  44394. BABYLON.serialize("useParallax")
  44395. ], StandardMaterial.prototype, "_useParallax", void 0);
  44396. __decorate([
  44397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44398. ], StandardMaterial.prototype, "useParallax", void 0);
  44399. __decorate([
  44400. BABYLON.serialize("useParallaxOcclusion")
  44401. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44402. __decorate([
  44403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44404. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44405. __decorate([
  44406. BABYLON.serialize()
  44407. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44408. __decorate([
  44409. BABYLON.serialize("roughness")
  44410. ], StandardMaterial.prototype, "_roughness", void 0);
  44411. __decorate([
  44412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44413. ], StandardMaterial.prototype, "roughness", void 0);
  44414. __decorate([
  44415. BABYLON.serialize()
  44416. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44417. __decorate([
  44418. BABYLON.serialize()
  44419. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44420. __decorate([
  44421. BABYLON.serialize()
  44422. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44423. __decorate([
  44424. BABYLON.serialize("useLightmapAsShadowmap")
  44425. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44426. __decorate([
  44427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44428. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44429. __decorate([
  44430. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44431. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44432. __decorate([
  44433. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44434. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44435. __decorate([
  44436. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44437. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44438. __decorate([
  44439. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44440. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44441. __decorate([
  44442. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44443. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44444. __decorate([
  44445. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44446. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44447. __decorate([
  44448. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44449. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44450. __decorate([
  44451. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44452. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44453. __decorate([
  44454. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44455. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44456. __decorate([
  44457. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44458. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44459. __decorate([
  44460. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44461. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44462. __decorate([
  44463. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44464. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44465. __decorate([
  44466. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44467. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44468. __decorate([
  44469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44470. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44471. __decorate([
  44472. BABYLON.serialize("maxSimultaneousLights")
  44473. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44474. __decorate([
  44475. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44476. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44477. __decorate([
  44478. BABYLON.serialize("invertNormalMapX")
  44479. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44480. __decorate([
  44481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44482. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44483. __decorate([
  44484. BABYLON.serialize("invertNormalMapY")
  44485. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44486. __decorate([
  44487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44488. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44489. __decorate([
  44490. BABYLON.serialize("twoSidedLighting")
  44491. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44492. __decorate([
  44493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44494. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44495. __decorate([
  44496. BABYLON.serialize()
  44497. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44498. return StandardMaterial;
  44499. }(BABYLON.PushMaterial));
  44500. BABYLON.StandardMaterial = StandardMaterial;
  44501. })(BABYLON || (BABYLON = {}));
  44502. //# sourceMappingURL=babylon.standardMaterial.js.map
  44503. var BABYLON;
  44504. (function (BABYLON) {
  44505. /**
  44506. * Manages the defines for the PBR Material.
  44507. * @hiddenChildren
  44508. */
  44509. var PBRMaterialDefines = /** @class */ (function (_super) {
  44510. __extends(PBRMaterialDefines, _super);
  44511. /**
  44512. * Initializes the PBR Material defines.
  44513. */
  44514. function PBRMaterialDefines() {
  44515. var _this = _super.call(this) || this;
  44516. _this.PBR = true;
  44517. _this.MAINUV1 = false;
  44518. _this.MAINUV2 = false;
  44519. _this.UV1 = false;
  44520. _this.UV2 = false;
  44521. _this.ALBEDO = false;
  44522. _this.ALBEDODIRECTUV = 0;
  44523. _this.VERTEXCOLOR = false;
  44524. _this.AMBIENT = false;
  44525. _this.AMBIENTDIRECTUV = 0;
  44526. _this.AMBIENTINGRAYSCALE = false;
  44527. _this.OPACITY = false;
  44528. _this.VERTEXALPHA = false;
  44529. _this.OPACITYDIRECTUV = 0;
  44530. _this.OPACITYRGB = false;
  44531. _this.ALPHATEST = false;
  44532. _this.DEPTHPREPASS = false;
  44533. _this.ALPHABLEND = false;
  44534. _this.ALPHAFROMALBEDO = false;
  44535. _this.ALPHATESTVALUE = "0.5";
  44536. _this.SPECULAROVERALPHA = false;
  44537. _this.RADIANCEOVERALPHA = false;
  44538. _this.ALPHAFRESNEL = false;
  44539. _this.LINEARALPHAFRESNEL = false;
  44540. _this.PREMULTIPLYALPHA = false;
  44541. _this.EMISSIVE = false;
  44542. _this.EMISSIVEDIRECTUV = 0;
  44543. _this.REFLECTIVITY = false;
  44544. _this.REFLECTIVITYDIRECTUV = 0;
  44545. _this.SPECULARTERM = false;
  44546. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44547. _this.MICROSURFACEAUTOMATIC = false;
  44548. _this.LODBASEDMICROSFURACE = false;
  44549. _this.MICROSURFACEMAP = false;
  44550. _this.MICROSURFACEMAPDIRECTUV = 0;
  44551. _this.METALLICWORKFLOW = false;
  44552. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44553. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44554. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44555. _this.AOSTOREINMETALMAPRED = false;
  44556. _this.ENVIRONMENTBRDF = false;
  44557. _this.NORMAL = false;
  44558. _this.TANGENT = false;
  44559. _this.BUMP = false;
  44560. _this.BUMPDIRECTUV = 0;
  44561. _this.OBJECTSPACE_NORMALMAP = false;
  44562. _this.PARALLAX = false;
  44563. _this.PARALLAXOCCLUSION = false;
  44564. _this.NORMALXYSCALE = true;
  44565. _this.LIGHTMAP = false;
  44566. _this.LIGHTMAPDIRECTUV = 0;
  44567. _this.USELIGHTMAPASSHADOWMAP = false;
  44568. _this.GAMMALIGHTMAP = false;
  44569. _this.REFLECTION = false;
  44570. _this.REFLECTIONMAP_3D = false;
  44571. _this.REFLECTIONMAP_SPHERICAL = false;
  44572. _this.REFLECTIONMAP_PLANAR = false;
  44573. _this.REFLECTIONMAP_CUBIC = false;
  44574. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44575. _this.REFLECTIONMAP_PROJECTION = false;
  44576. _this.REFLECTIONMAP_SKYBOX = false;
  44577. _this.REFLECTIONMAP_EXPLICIT = false;
  44578. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44579. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44580. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44581. _this.INVERTCUBICMAP = false;
  44582. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44583. _this.USESPHERICALINVERTEX = false;
  44584. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44585. _this.LODINREFLECTIONALPHA = false;
  44586. _this.GAMMAREFLECTION = false;
  44587. _this.RADIANCEOCCLUSION = false;
  44588. _this.HORIZONOCCLUSION = false;
  44589. _this.REFRACTION = false;
  44590. _this.REFRACTIONMAP_3D = false;
  44591. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44592. _this.LODINREFRACTIONALPHA = false;
  44593. _this.GAMMAREFRACTION = false;
  44594. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44595. _this.INSTANCES = false;
  44596. _this.NUM_BONE_INFLUENCERS = 0;
  44597. _this.BonesPerMesh = 0;
  44598. _this.NONUNIFORMSCALING = false;
  44599. _this.MORPHTARGETS = false;
  44600. _this.MORPHTARGETS_NORMAL = false;
  44601. _this.MORPHTARGETS_TANGENT = false;
  44602. _this.NUM_MORPH_INFLUENCERS = 0;
  44603. _this.IMAGEPROCESSING = false;
  44604. _this.VIGNETTE = false;
  44605. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44606. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44607. _this.TONEMAPPING = false;
  44608. _this.CONTRAST = false;
  44609. _this.COLORCURVES = false;
  44610. _this.COLORGRADING = false;
  44611. _this.COLORGRADING3D = false;
  44612. _this.SAMPLER3DGREENDEPTH = false;
  44613. _this.SAMPLER3DBGRMAP = false;
  44614. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44615. _this.EXPOSURE = false;
  44616. _this.USEPHYSICALLIGHTFALLOFF = false;
  44617. _this.TWOSIDEDLIGHTING = false;
  44618. _this.SHADOWFLOAT = false;
  44619. _this.CLIPPLANE = false;
  44620. _this.POINTSIZE = false;
  44621. _this.FOG = false;
  44622. _this.LOGARITHMICDEPTH = false;
  44623. _this.FORCENORMALFORWARD = false;
  44624. _this.SPECULARAA = false;
  44625. _this.UNLIT = false;
  44626. _this.rebuild();
  44627. return _this;
  44628. }
  44629. /**
  44630. * Resets the PBR Material defines.
  44631. */
  44632. PBRMaterialDefines.prototype.reset = function () {
  44633. _super.prototype.reset.call(this);
  44634. this.ALPHATESTVALUE = "0.5";
  44635. this.PBR = true;
  44636. };
  44637. return PBRMaterialDefines;
  44638. }(BABYLON.MaterialDefines));
  44639. /**
  44640. * The Physically based material base class of BJS.
  44641. *
  44642. * This offers the main features of a standard PBR material.
  44643. * For more information, please refer to the documentation :
  44644. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44645. */
  44646. var PBRBaseMaterial = /** @class */ (function (_super) {
  44647. __extends(PBRBaseMaterial, _super);
  44648. /**
  44649. * Instantiates a new PBRMaterial instance.
  44650. *
  44651. * @param name The material name
  44652. * @param scene The scene the material will be use in.
  44653. */
  44654. function PBRBaseMaterial(name, scene) {
  44655. var _this = _super.call(this, name, scene) || this;
  44656. /**
  44657. * Intensity of the direct lights e.g. the four lights available in your scene.
  44658. * This impacts both the direct diffuse and specular highlights.
  44659. */
  44660. _this._directIntensity = 1.0;
  44661. /**
  44662. * Intensity of the emissive part of the material.
  44663. * This helps controlling the emissive effect without modifying the emissive color.
  44664. */
  44665. _this._emissiveIntensity = 1.0;
  44666. /**
  44667. * Intensity of the environment e.g. how much the environment will light the object
  44668. * either through harmonics for rough material or through the refelction for shiny ones.
  44669. */
  44670. _this._environmentIntensity = 1.0;
  44671. /**
  44672. * This is a special control allowing the reduction of the specular highlights coming from the
  44673. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44674. */
  44675. _this._specularIntensity = 1.0;
  44676. /**
  44677. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44678. */
  44679. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44680. /**
  44681. * Debug Control allowing disabling the bump map on this material.
  44682. */
  44683. _this._disableBumpMap = false;
  44684. /**
  44685. * AKA Occlusion Texture Intensity in other nomenclature.
  44686. */
  44687. _this._ambientTextureStrength = 1.0;
  44688. /**
  44689. * The color of a material in ambient lighting.
  44690. */
  44691. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44692. /**
  44693. * AKA Diffuse Color in other nomenclature.
  44694. */
  44695. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44696. /**
  44697. * AKA Specular Color in other nomenclature.
  44698. */
  44699. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44700. /**
  44701. * The color applied when light is reflected from a material.
  44702. */
  44703. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44704. /**
  44705. * The color applied when light is emitted from a material.
  44706. */
  44707. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44708. /**
  44709. * AKA Glossiness in other nomenclature.
  44710. */
  44711. _this._microSurface = 0.9;
  44712. /**
  44713. * source material index of refraction (IOR)' / 'destination material IOR.
  44714. */
  44715. _this._indexOfRefraction = 0.66;
  44716. /**
  44717. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44718. */
  44719. _this._invertRefractionY = false;
  44720. /**
  44721. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44722. * Materials half opaque for instance using refraction could benefit from this control.
  44723. */
  44724. _this._linkRefractionWithTransparency = false;
  44725. /**
  44726. * Specifies that the material will use the light map as a show map.
  44727. */
  44728. _this._useLightmapAsShadowmap = false;
  44729. /**
  44730. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44731. * makes the reflect vector face the model (under horizon).
  44732. */
  44733. _this._useHorizonOcclusion = true;
  44734. /**
  44735. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44736. * too much the area relying on ambient texture to define their ambient occlusion.
  44737. */
  44738. _this._useRadianceOcclusion = true;
  44739. /**
  44740. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44741. */
  44742. _this._useAlphaFromAlbedoTexture = false;
  44743. /**
  44744. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44745. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44746. */
  44747. _this._useSpecularOverAlpha = true;
  44748. /**
  44749. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44750. */
  44751. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44752. /**
  44753. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44754. */
  44755. _this._useRoughnessFromMetallicTextureAlpha = true;
  44756. /**
  44757. * Specifies if the metallic texture contains the roughness information in its green channel.
  44758. */
  44759. _this._useRoughnessFromMetallicTextureGreen = false;
  44760. /**
  44761. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44762. */
  44763. _this._useMetallnessFromMetallicTextureBlue = false;
  44764. /**
  44765. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44766. */
  44767. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44768. /**
  44769. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44770. */
  44771. _this._useAmbientInGrayScale = false;
  44772. /**
  44773. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44774. * The material will try to infer what glossiness each pixel should be.
  44775. */
  44776. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44777. /**
  44778. * BJS is using an harcoded light falloff based on a manually sets up range.
  44779. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44780. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44781. */
  44782. _this._usePhysicalLightFalloff = true;
  44783. /**
  44784. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44785. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44786. */
  44787. _this._useRadianceOverAlpha = true;
  44788. /**
  44789. * Allows using an object space normal map (instead of tangent space).
  44790. */
  44791. _this._useObjectSpaceNormalMap = false;
  44792. /**
  44793. * Allows using the bump map in parallax mode.
  44794. */
  44795. _this._useParallax = false;
  44796. /**
  44797. * Allows using the bump map in parallax occlusion mode.
  44798. */
  44799. _this._useParallaxOcclusion = false;
  44800. /**
  44801. * Controls the scale bias of the parallax mode.
  44802. */
  44803. _this._parallaxScaleBias = 0.05;
  44804. /**
  44805. * If sets to true, disables all the lights affecting the material.
  44806. */
  44807. _this._disableLighting = false;
  44808. /**
  44809. * Number of Simultaneous lights allowed on the material.
  44810. */
  44811. _this._maxSimultaneousLights = 4;
  44812. /**
  44813. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44814. */
  44815. _this._invertNormalMapX = false;
  44816. /**
  44817. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44818. */
  44819. _this._invertNormalMapY = false;
  44820. /**
  44821. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44822. */
  44823. _this._twoSidedLighting = false;
  44824. /**
  44825. * Defines the alpha limits in alpha test mode.
  44826. */
  44827. _this._alphaCutOff = 0.4;
  44828. /**
  44829. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44830. */
  44831. _this._forceAlphaTest = false;
  44832. /**
  44833. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44834. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44835. */
  44836. _this._useAlphaFresnel = false;
  44837. /**
  44838. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44839. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44840. */
  44841. _this._useLinearAlphaFresnel = false;
  44842. /**
  44843. * The transparency mode of the material.
  44844. */
  44845. _this._transparencyMode = null;
  44846. /**
  44847. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44848. * from cos thetav and roughness:
  44849. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44850. */
  44851. _this._environmentBRDFTexture = null;
  44852. /**
  44853. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44854. */
  44855. _this._forceIrradianceInFragment = false;
  44856. /**
  44857. * Force normal to face away from face.
  44858. */
  44859. _this._forceNormalForward = false;
  44860. /**
  44861. * Enables specular anti aliasing in the PBR shader.
  44862. * It will both interacts on the Geometry for analytical and IBL lighting.
  44863. * It also prefilter the roughness map based on the bump values.
  44864. */
  44865. _this._enableSpecularAntiAliasing = false;
  44866. /**
  44867. * Stores the available render targets.
  44868. */
  44869. _this._renderTargets = new BABYLON.SmartArray(16);
  44870. /**
  44871. * Sets the global ambient color for the material used in lighting calculations.
  44872. */
  44873. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44874. /**
  44875. * If set to true, no lighting calculations will be applied.
  44876. */
  44877. _this._unlit = false;
  44878. // Setup the default processing configuration to the scene.
  44879. _this._attachImageProcessingConfiguration(null);
  44880. _this.getRenderTargetTextures = function () {
  44881. _this._renderTargets.reset();
  44882. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44883. _this._renderTargets.push(_this._reflectionTexture);
  44884. }
  44885. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44886. _this._renderTargets.push(_this._refractionTexture);
  44887. }
  44888. return _this._renderTargets;
  44889. };
  44890. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44891. return _this;
  44892. }
  44893. /**
  44894. * Attaches a new image processing configuration to the PBR Material.
  44895. * @param configuration
  44896. */
  44897. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44898. var _this = this;
  44899. if (configuration === this._imageProcessingConfiguration) {
  44900. return;
  44901. }
  44902. // Detaches observer.
  44903. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44904. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44905. }
  44906. // Pick the scene configuration if needed.
  44907. if (!configuration) {
  44908. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44909. }
  44910. else {
  44911. this._imageProcessingConfiguration = configuration;
  44912. }
  44913. // Attaches observer.
  44914. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44915. _this._markAllSubMeshesAsImageProcessingDirty();
  44916. });
  44917. };
  44918. /**
  44919. * Gets the name of the material class.
  44920. */
  44921. PBRBaseMaterial.prototype.getClassName = function () {
  44922. return "PBRBaseMaterial";
  44923. };
  44924. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44925. /**
  44926. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44927. */
  44928. get: function () {
  44929. return this._useLogarithmicDepth;
  44930. },
  44931. /**
  44932. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44933. */
  44934. set: function (value) {
  44935. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44936. },
  44937. enumerable: true,
  44938. configurable: true
  44939. });
  44940. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44941. /**
  44942. * Gets the current transparency mode.
  44943. */
  44944. get: function () {
  44945. return this._transparencyMode;
  44946. },
  44947. /**
  44948. * Sets the transparency mode of the material.
  44949. */
  44950. set: function (value) {
  44951. if (this._transparencyMode === value) {
  44952. return;
  44953. }
  44954. this._transparencyMode = value;
  44955. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44956. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44957. },
  44958. enumerable: true,
  44959. configurable: true
  44960. });
  44961. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44962. /**
  44963. * Returns true if alpha blending should be disabled.
  44964. */
  44965. get: function () {
  44966. return (this._linkRefractionWithTransparency ||
  44967. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44968. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44969. },
  44970. enumerable: true,
  44971. configurable: true
  44972. });
  44973. /**
  44974. * Specifies whether or not this material should be rendered in alpha blend mode.
  44975. */
  44976. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44977. if (this._disableAlphaBlending) {
  44978. return false;
  44979. }
  44980. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44981. };
  44982. /**
  44983. * Specifies if the mesh will require alpha blending.
  44984. * @param mesh - BJS mesh.
  44985. */
  44986. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44987. if (this._disableAlphaBlending) {
  44988. return false;
  44989. }
  44990. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44991. };
  44992. /**
  44993. * Specifies whether or not this material should be rendered in alpha test mode.
  44994. */
  44995. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44996. if (this._forceAlphaTest) {
  44997. return true;
  44998. }
  44999. if (this._linkRefractionWithTransparency) {
  45000. return false;
  45001. }
  45002. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45003. };
  45004. /**
  45005. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45006. */
  45007. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45008. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45009. };
  45010. /**
  45011. * Gets the texture used for the alpha test.
  45012. */
  45013. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45014. return this._albedoTexture;
  45015. };
  45016. /**
  45017. * Specifies that the submesh is ready to be used.
  45018. * @param mesh - BJS mesh.
  45019. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45020. * @param useInstances - Specifies that instances should be used.
  45021. * @returns - boolean indicating that the submesh is ready or not.
  45022. */
  45023. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45024. if (subMesh.effect && this.isFrozen) {
  45025. if (this._wasPreviouslyReady) {
  45026. return true;
  45027. }
  45028. }
  45029. if (!subMesh._materialDefines) {
  45030. subMesh._materialDefines = new PBRMaterialDefines();
  45031. }
  45032. var defines = subMesh._materialDefines;
  45033. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45034. if (defines._renderId === this.getScene().getRenderId()) {
  45035. return true;
  45036. }
  45037. }
  45038. var scene = this.getScene();
  45039. var engine = scene.getEngine();
  45040. if (defines._areTexturesDirty) {
  45041. if (scene.texturesEnabled) {
  45042. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45043. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45044. return false;
  45045. }
  45046. }
  45047. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45048. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45049. return false;
  45050. }
  45051. }
  45052. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45053. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45054. return false;
  45055. }
  45056. }
  45057. var reflectionTexture = this._getReflectionTexture();
  45058. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45059. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45060. return false;
  45061. }
  45062. }
  45063. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45064. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45065. return false;
  45066. }
  45067. }
  45068. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45069. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45070. return false;
  45071. }
  45072. }
  45073. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45074. if (this._metallicTexture) {
  45075. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45076. return false;
  45077. }
  45078. }
  45079. else if (this._reflectivityTexture) {
  45080. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45081. return false;
  45082. }
  45083. }
  45084. if (this._microSurfaceTexture) {
  45085. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45086. return false;
  45087. }
  45088. }
  45089. }
  45090. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45091. // Bump texture cannot be not blocking.
  45092. if (!this._bumpTexture.isReady()) {
  45093. return false;
  45094. }
  45095. }
  45096. var refractionTexture = this._getRefractionTexture();
  45097. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45098. if (!refractionTexture.isReadyOrNotBlocking()) {
  45099. return false;
  45100. }
  45101. }
  45102. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45103. // This is blocking.
  45104. if (!this._environmentBRDFTexture.isReady()) {
  45105. return false;
  45106. }
  45107. }
  45108. }
  45109. }
  45110. if (defines._areImageProcessingDirty) {
  45111. if (!this._imageProcessingConfiguration.isReady()) {
  45112. return false;
  45113. }
  45114. }
  45115. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45116. mesh.createNormals(true);
  45117. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45118. }
  45119. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45120. if (effect) {
  45121. scene.resetCachedMaterial();
  45122. subMesh.setEffect(effect, defines);
  45123. this.buildUniformLayout();
  45124. }
  45125. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45126. return false;
  45127. }
  45128. defines._renderId = scene.getRenderId();
  45129. this._wasPreviouslyReady = true;
  45130. return true;
  45131. };
  45132. /**
  45133. * Specifies if the material uses metallic roughness workflow.
  45134. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45135. */
  45136. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45137. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45138. return true;
  45139. }
  45140. return false;
  45141. };
  45142. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45143. if (onCompiled === void 0) { onCompiled = null; }
  45144. if (onError === void 0) { onError = null; }
  45145. if (useInstances === void 0) { useInstances = null; }
  45146. if (useClipPlane === void 0) { useClipPlane = null; }
  45147. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45148. if (!defines.isDirty) {
  45149. return null;
  45150. }
  45151. defines.markAsProcessed();
  45152. var scene = this.getScene();
  45153. var engine = scene.getEngine();
  45154. // Fallbacks
  45155. var fallbacks = new BABYLON.EffectFallbacks();
  45156. var fallbackRank = 0;
  45157. if (defines.USESPHERICALINVERTEX) {
  45158. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45159. }
  45160. if (defines.FOG) {
  45161. fallbacks.addFallback(fallbackRank, "FOG");
  45162. }
  45163. if (defines.SPECULARAA) {
  45164. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45165. }
  45166. if (defines.POINTSIZE) {
  45167. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45168. }
  45169. if (defines.LOGARITHMICDEPTH) {
  45170. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45171. }
  45172. if (defines.PARALLAX) {
  45173. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45174. }
  45175. if (defines.PARALLAXOCCLUSION) {
  45176. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45177. }
  45178. if (defines.ENVIRONMENTBRDF) {
  45179. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45180. }
  45181. if (defines.TANGENT) {
  45182. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45183. }
  45184. if (defines.BUMP) {
  45185. fallbacks.addFallback(fallbackRank++, "BUMP");
  45186. }
  45187. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45188. if (defines.SPECULARTERM) {
  45189. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45190. }
  45191. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45192. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45193. }
  45194. if (defines.LIGHTMAP) {
  45195. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45196. }
  45197. if (defines.NORMAL) {
  45198. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45199. }
  45200. if (defines.AMBIENT) {
  45201. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45202. }
  45203. if (defines.EMISSIVE) {
  45204. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45205. }
  45206. if (defines.VERTEXCOLOR) {
  45207. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45208. }
  45209. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45210. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45211. }
  45212. if (defines.MORPHTARGETS) {
  45213. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45214. }
  45215. //Attributes
  45216. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45217. if (defines.NORMAL) {
  45218. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45219. }
  45220. if (defines.TANGENT) {
  45221. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45222. }
  45223. if (defines.UV1) {
  45224. attribs.push(BABYLON.VertexBuffer.UVKind);
  45225. }
  45226. if (defines.UV2) {
  45227. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45228. }
  45229. if (defines.VERTEXCOLOR) {
  45230. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45231. }
  45232. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45233. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45234. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45235. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45236. "vFogInfos", "vFogColor", "pointSize",
  45237. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45238. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45239. "mBones",
  45240. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45241. "vLightingIntensity",
  45242. "logarithmicDepthConstant",
  45243. "vSphericalX", "vSphericalY", "vSphericalZ",
  45244. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45245. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45246. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45247. "vTangentSpaceParams"
  45248. ];
  45249. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45250. "bumpSampler", "lightmapSampler", "opacitySampler",
  45251. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45252. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45253. "microSurfaceSampler", "environmentBrdfSampler"];
  45254. var uniformBuffers = ["Material", "Scene"];
  45255. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45256. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45257. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45258. uniformsNames: uniforms,
  45259. uniformBuffersNames: uniformBuffers,
  45260. samplers: samplers,
  45261. defines: defines,
  45262. maxSimultaneousLights: this._maxSimultaneousLights
  45263. });
  45264. var join = defines.toString();
  45265. return engine.createEffect("pbr", {
  45266. attributes: attribs,
  45267. uniformsNames: uniforms,
  45268. uniformBuffersNames: uniformBuffers,
  45269. samplers: samplers,
  45270. defines: join,
  45271. fallbacks: fallbacks,
  45272. onCompiled: onCompiled,
  45273. onError: onError,
  45274. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45275. }, engine);
  45276. };
  45277. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45278. if (useInstances === void 0) { useInstances = null; }
  45279. if (useClipPlane === void 0) { useClipPlane = null; }
  45280. var scene = this.getScene();
  45281. var engine = scene.getEngine();
  45282. // Lights
  45283. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45284. defines._needNormals = true;
  45285. // Textures
  45286. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45287. if (defines._areTexturesDirty) {
  45288. defines._needUVs = false;
  45289. if (scene.texturesEnabled) {
  45290. if (scene.getEngine().getCaps().textureLOD) {
  45291. defines.LODBASEDMICROSFURACE = true;
  45292. }
  45293. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45295. }
  45296. else {
  45297. defines.ALBEDO = false;
  45298. }
  45299. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45301. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45302. }
  45303. else {
  45304. defines.AMBIENT = false;
  45305. }
  45306. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45307. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45308. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45309. }
  45310. else {
  45311. defines.OPACITY = false;
  45312. }
  45313. var reflectionTexture = this._getReflectionTexture();
  45314. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45315. defines.REFLECTION = true;
  45316. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45317. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45318. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45319. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45320. defines.INVERTCUBICMAP = true;
  45321. }
  45322. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45323. switch (reflectionTexture.coordinatesMode) {
  45324. case BABYLON.Texture.EXPLICIT_MODE:
  45325. defines.REFLECTIONMAP_EXPLICIT = true;
  45326. break;
  45327. case BABYLON.Texture.PLANAR_MODE:
  45328. defines.REFLECTIONMAP_PLANAR = true;
  45329. break;
  45330. case BABYLON.Texture.PROJECTION_MODE:
  45331. defines.REFLECTIONMAP_PROJECTION = true;
  45332. break;
  45333. case BABYLON.Texture.SKYBOX_MODE:
  45334. defines.REFLECTIONMAP_SKYBOX = true;
  45335. break;
  45336. case BABYLON.Texture.SPHERICAL_MODE:
  45337. defines.REFLECTIONMAP_SPHERICAL = true;
  45338. break;
  45339. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45340. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45341. break;
  45342. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45343. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45344. break;
  45345. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45346. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45347. break;
  45348. case BABYLON.Texture.CUBIC_MODE:
  45349. case BABYLON.Texture.INVCUBIC_MODE:
  45350. default:
  45351. defines.REFLECTIONMAP_CUBIC = true;
  45352. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45353. break;
  45354. }
  45355. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45356. if (reflectionTexture.sphericalPolynomial) {
  45357. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45358. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45359. defines.USESPHERICALINVERTEX = false;
  45360. }
  45361. else {
  45362. defines.USESPHERICALINVERTEX = true;
  45363. }
  45364. }
  45365. }
  45366. }
  45367. else {
  45368. defines.REFLECTION = false;
  45369. defines.REFLECTIONMAP_3D = false;
  45370. defines.REFLECTIONMAP_SPHERICAL = false;
  45371. defines.REFLECTIONMAP_PLANAR = false;
  45372. defines.REFLECTIONMAP_CUBIC = false;
  45373. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45374. defines.REFLECTIONMAP_PROJECTION = false;
  45375. defines.REFLECTIONMAP_SKYBOX = false;
  45376. defines.REFLECTIONMAP_EXPLICIT = false;
  45377. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45378. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45379. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45380. defines.INVERTCUBICMAP = false;
  45381. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45382. defines.USESPHERICALINVERTEX = false;
  45383. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45384. defines.LODINREFLECTIONALPHA = false;
  45385. defines.GAMMAREFLECTION = false;
  45386. }
  45387. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45389. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45390. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45391. }
  45392. else {
  45393. defines.LIGHTMAP = false;
  45394. }
  45395. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45396. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45397. }
  45398. else {
  45399. defines.EMISSIVE = false;
  45400. }
  45401. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45402. if (this._metallicTexture) {
  45403. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45404. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45405. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45406. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45407. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45408. }
  45409. else if (this._reflectivityTexture) {
  45410. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45411. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45412. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45413. }
  45414. else {
  45415. defines.REFLECTIVITY = false;
  45416. }
  45417. if (this._microSurfaceTexture) {
  45418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45419. }
  45420. else {
  45421. defines.MICROSURFACEMAP = false;
  45422. }
  45423. }
  45424. else {
  45425. defines.REFLECTIVITY = false;
  45426. defines.MICROSURFACEMAP = false;
  45427. }
  45428. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45430. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45431. defines.PARALLAX = true;
  45432. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45433. }
  45434. else {
  45435. defines.PARALLAX = false;
  45436. }
  45437. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45438. }
  45439. else {
  45440. defines.BUMP = false;
  45441. }
  45442. var refractionTexture = this._getRefractionTexture();
  45443. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45444. defines.REFRACTION = true;
  45445. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45446. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45447. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45448. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45449. if (this._linkRefractionWithTransparency) {
  45450. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45451. }
  45452. }
  45453. else {
  45454. defines.REFRACTION = false;
  45455. }
  45456. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45457. defines.ENVIRONMENTBRDF = true;
  45458. }
  45459. else {
  45460. defines.ENVIRONMENTBRDF = false;
  45461. }
  45462. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45463. defines.ALPHAFROMALBEDO = true;
  45464. }
  45465. else {
  45466. defines.ALPHAFROMALBEDO = false;
  45467. }
  45468. }
  45469. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45470. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45471. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45472. if (!this.backFaceCulling && this._twoSidedLighting) {
  45473. defines.TWOSIDEDLIGHTING = true;
  45474. }
  45475. else {
  45476. defines.TWOSIDEDLIGHTING = false;
  45477. }
  45478. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45479. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45480. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45481. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45482. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45483. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45484. }
  45485. if (defines._areImageProcessingDirty) {
  45486. this._imageProcessingConfiguration.prepareDefines(defines);
  45487. }
  45488. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45489. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45490. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45491. // Misc.
  45492. if (defines._areMiscDirty) {
  45493. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45494. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45495. }
  45496. // Values that need to be evaluated on every frame
  45497. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45498. // Attribs
  45499. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45500. };
  45501. /**
  45502. * Force shader compilation
  45503. */
  45504. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45505. var _this = this;
  45506. var localOptions = __assign({ clipPlane: false }, options);
  45507. var defines = new PBRMaterialDefines();
  45508. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45509. if (effect.isReady()) {
  45510. if (onCompiled) {
  45511. onCompiled(this);
  45512. }
  45513. }
  45514. else {
  45515. effect.onCompileObservable.add(function () {
  45516. if (onCompiled) {
  45517. onCompiled(_this);
  45518. }
  45519. });
  45520. }
  45521. };
  45522. /**
  45523. * Initializes the uniform buffer layout for the shader.
  45524. */
  45525. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45526. // Order is important !
  45527. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45528. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45529. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45530. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45531. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45532. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45533. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45534. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45535. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45536. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45537. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45538. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45539. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45540. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45541. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45542. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45543. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45544. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45545. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45546. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45547. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45548. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45549. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45550. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45551. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45552. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45553. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45554. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45555. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45556. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45557. this._uniformBuffer.addUniform("pointSize", 1);
  45558. this._uniformBuffer.create();
  45559. };
  45560. /**
  45561. * Unbinds the textures.
  45562. */
  45563. PBRBaseMaterial.prototype.unbind = function () {
  45564. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45565. this._uniformBuffer.setTexture("reflectionSampler", null);
  45566. }
  45567. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45568. this._uniformBuffer.setTexture("refractionSampler", null);
  45569. }
  45570. _super.prototype.unbind.call(this);
  45571. };
  45572. /**
  45573. * Binds the submesh data.
  45574. * @param world - The world matrix.
  45575. * @param mesh - The BJS mesh.
  45576. * @param subMesh - A submesh of the BJS mesh.
  45577. */
  45578. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45579. var scene = this.getScene();
  45580. var defines = subMesh._materialDefines;
  45581. if (!defines) {
  45582. return;
  45583. }
  45584. var effect = subMesh.effect;
  45585. if (!effect) {
  45586. return;
  45587. }
  45588. this._activeEffect = effect;
  45589. // Matrices
  45590. this.bindOnlyWorldMatrix(world);
  45591. // Normal Matrix
  45592. if (defines.OBJECTSPACE_NORMALMAP) {
  45593. world.toNormalMatrix(this._normalMatrix);
  45594. this.bindOnlyNormalMatrix(this._normalMatrix);
  45595. }
  45596. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45597. // Bones
  45598. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45599. var reflectionTexture = null;
  45600. if (mustRebind) {
  45601. this._uniformBuffer.bindToEffect(effect, "Material");
  45602. this.bindViewProjection(effect);
  45603. reflectionTexture = this._getReflectionTexture();
  45604. var refractionTexture = this._getRefractionTexture();
  45605. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45606. // Texture uniforms
  45607. if (scene.texturesEnabled) {
  45608. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45609. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45610. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45611. }
  45612. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45613. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45614. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45615. }
  45616. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45617. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45618. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45619. }
  45620. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45621. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45622. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45623. if (reflectionTexture.boundingBoxSize) {
  45624. var cubeTexture = reflectionTexture;
  45625. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45626. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45627. }
  45628. var polynomials = reflectionTexture.sphericalPolynomial;
  45629. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45630. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45631. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45632. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45633. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45634. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45635. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45636. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45637. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45638. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45639. }
  45640. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45641. }
  45642. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45643. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45644. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45645. }
  45646. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45647. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45648. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45649. }
  45650. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45651. if (this._metallicTexture) {
  45652. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45653. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45654. }
  45655. else if (this._reflectivityTexture) {
  45656. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45657. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45658. }
  45659. if (this._microSurfaceTexture) {
  45660. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45661. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45662. }
  45663. }
  45664. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45665. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45666. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45667. if (scene._mirroredCameraPosition) {
  45668. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45669. }
  45670. else {
  45671. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45672. }
  45673. }
  45674. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45675. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45676. var depth = 1.0;
  45677. if (!refractionTexture.isCube) {
  45678. if (refractionTexture.depth) {
  45679. depth = refractionTexture.depth;
  45680. }
  45681. }
  45682. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45683. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45684. }
  45685. }
  45686. // Point size
  45687. if (this.pointsCloud) {
  45688. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45689. }
  45690. // Colors
  45691. if (defines.METALLICWORKFLOW) {
  45692. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45693. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45694. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45695. }
  45696. else {
  45697. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45698. }
  45699. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45700. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45701. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45702. // Misc
  45703. this._lightingInfos.x = this._directIntensity;
  45704. this._lightingInfos.y = this._emissiveIntensity;
  45705. this._lightingInfos.z = this._environmentIntensity;
  45706. this._lightingInfos.w = this._specularIntensity;
  45707. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45708. }
  45709. // Textures
  45710. if (scene.texturesEnabled) {
  45711. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45712. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45713. }
  45714. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45715. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45716. }
  45717. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45718. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45719. }
  45720. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45721. if (defines.LODBASEDMICROSFURACE) {
  45722. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45723. }
  45724. else {
  45725. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45726. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45727. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45728. }
  45729. }
  45730. if (defines.ENVIRONMENTBRDF) {
  45731. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45732. }
  45733. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45734. if (defines.LODBASEDMICROSFURACE) {
  45735. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45736. }
  45737. else {
  45738. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45739. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45740. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45741. }
  45742. }
  45743. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45744. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45745. }
  45746. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45747. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45748. }
  45749. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45750. if (this._metallicTexture) {
  45751. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45752. }
  45753. else if (this._reflectivityTexture) {
  45754. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45755. }
  45756. if (this._microSurfaceTexture) {
  45757. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45758. }
  45759. }
  45760. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45761. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45762. }
  45763. }
  45764. // Clip plane
  45765. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45766. // Colors
  45767. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45768. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45769. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45770. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45771. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45772. }
  45773. if (mustRebind || !this.isFrozen) {
  45774. // Lights
  45775. if (scene.lightsEnabled && !this._disableLighting) {
  45776. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45777. }
  45778. // View
  45779. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45780. this.bindView(effect);
  45781. }
  45782. // Fog
  45783. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45784. // Morph targets
  45785. if (defines.NUM_MORPH_INFLUENCERS) {
  45786. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45787. }
  45788. // image processing
  45789. this._imageProcessingConfiguration.bind(this._activeEffect);
  45790. // Log. depth
  45791. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45792. }
  45793. this._uniformBuffer.update();
  45794. this._afterBind(mesh, this._activeEffect);
  45795. };
  45796. /**
  45797. * Returns the animatable textures.
  45798. * @returns - Array of animatable textures.
  45799. */
  45800. PBRBaseMaterial.prototype.getAnimatables = function () {
  45801. var results = [];
  45802. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45803. results.push(this._albedoTexture);
  45804. }
  45805. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45806. results.push(this._ambientTexture);
  45807. }
  45808. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45809. results.push(this._opacityTexture);
  45810. }
  45811. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45812. results.push(this._reflectionTexture);
  45813. }
  45814. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45815. results.push(this._emissiveTexture);
  45816. }
  45817. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45818. results.push(this._metallicTexture);
  45819. }
  45820. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45821. results.push(this._reflectivityTexture);
  45822. }
  45823. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45824. results.push(this._bumpTexture);
  45825. }
  45826. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45827. results.push(this._lightmapTexture);
  45828. }
  45829. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45830. results.push(this._refractionTexture);
  45831. }
  45832. return results;
  45833. };
  45834. /**
  45835. * Returns the texture used for reflections.
  45836. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45837. */
  45838. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45839. if (this._reflectionTexture) {
  45840. return this._reflectionTexture;
  45841. }
  45842. return this.getScene().environmentTexture;
  45843. };
  45844. /**
  45845. * Returns the texture used for refraction or null if none is used.
  45846. * @returns - Refection texture if present. If no refraction texture and refraction
  45847. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45848. */
  45849. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45850. if (this._refractionTexture) {
  45851. return this._refractionTexture;
  45852. }
  45853. if (this._linkRefractionWithTransparency) {
  45854. return this.getScene().environmentTexture;
  45855. }
  45856. return null;
  45857. };
  45858. /**
  45859. * Disposes the resources of the material.
  45860. * @param forceDisposeEffect - Forces the disposal of effects.
  45861. * @param forceDisposeTextures - Forces the disposal of all textures.
  45862. */
  45863. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45864. if (forceDisposeTextures) {
  45865. if (this._albedoTexture) {
  45866. this._albedoTexture.dispose();
  45867. }
  45868. if (this._ambientTexture) {
  45869. this._ambientTexture.dispose();
  45870. }
  45871. if (this._opacityTexture) {
  45872. this._opacityTexture.dispose();
  45873. }
  45874. if (this._reflectionTexture) {
  45875. this._reflectionTexture.dispose();
  45876. }
  45877. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45878. this._environmentBRDFTexture.dispose();
  45879. }
  45880. if (this._emissiveTexture) {
  45881. this._emissiveTexture.dispose();
  45882. }
  45883. if (this._metallicTexture) {
  45884. this._metallicTexture.dispose();
  45885. }
  45886. if (this._reflectivityTexture) {
  45887. this._reflectivityTexture.dispose();
  45888. }
  45889. if (this._bumpTexture) {
  45890. this._bumpTexture.dispose();
  45891. }
  45892. if (this._lightmapTexture) {
  45893. this._lightmapTexture.dispose();
  45894. }
  45895. if (this._refractionTexture) {
  45896. this._refractionTexture.dispose();
  45897. }
  45898. }
  45899. this._renderTargets.dispose();
  45900. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45901. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45902. }
  45903. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45904. };
  45905. /**
  45906. * Stores the reflectivity values based on metallic roughness workflow.
  45907. */
  45908. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45909. __decorate([
  45910. BABYLON.serializeAsImageProcessingConfiguration()
  45911. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45912. __decorate([
  45913. BABYLON.serialize()
  45914. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45915. __decorate([
  45916. BABYLON.serialize()
  45917. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45918. return PBRBaseMaterial;
  45919. }(BABYLON.PushMaterial));
  45920. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45921. })(BABYLON || (BABYLON = {}));
  45922. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45923. var BABYLON;
  45924. (function (BABYLON) {
  45925. /**
  45926. * The Physically based simple base material of BJS.
  45927. *
  45928. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45929. * It is used as the base class for both the specGloss and metalRough conventions.
  45930. */
  45931. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45932. __extends(PBRBaseSimpleMaterial, _super);
  45933. /**
  45934. * Instantiates a new PBRMaterial instance.
  45935. *
  45936. * @param name The material name
  45937. * @param scene The scene the material will be use in.
  45938. */
  45939. function PBRBaseSimpleMaterial(name, scene) {
  45940. var _this = _super.call(this, name, scene) || this;
  45941. /**
  45942. * Number of Simultaneous lights allowed on the material.
  45943. */
  45944. _this.maxSimultaneousLights = 4;
  45945. /**
  45946. * If sets to true, disables all the lights affecting the material.
  45947. */
  45948. _this.disableLighting = false;
  45949. /**
  45950. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45951. */
  45952. _this.invertNormalMapX = false;
  45953. /**
  45954. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45955. */
  45956. _this.invertNormalMapY = false;
  45957. /**
  45958. * Emissivie color used to self-illuminate the model.
  45959. */
  45960. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45961. /**
  45962. * Occlusion Channel Strenght.
  45963. */
  45964. _this.occlusionStrength = 1.0;
  45965. _this.useLightmapAsShadowmap = false;
  45966. _this._useAlphaFromAlbedoTexture = true;
  45967. _this._useAmbientInGrayScale = true;
  45968. return _this;
  45969. }
  45970. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45971. /**
  45972. * Gets the current double sided mode.
  45973. */
  45974. get: function () {
  45975. return this._twoSidedLighting;
  45976. },
  45977. /**
  45978. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45979. */
  45980. set: function (value) {
  45981. if (this._twoSidedLighting === value) {
  45982. return;
  45983. }
  45984. this._twoSidedLighting = value;
  45985. this.backFaceCulling = !value;
  45986. this._markAllSubMeshesAsTexturesDirty();
  45987. },
  45988. enumerable: true,
  45989. configurable: true
  45990. });
  45991. /**
  45992. * Return the active textures of the material.
  45993. */
  45994. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45995. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45996. if (this.environmentTexture) {
  45997. activeTextures.push(this.environmentTexture);
  45998. }
  45999. if (this.normalTexture) {
  46000. activeTextures.push(this.normalTexture);
  46001. }
  46002. if (this.emissiveTexture) {
  46003. activeTextures.push(this.emissiveTexture);
  46004. }
  46005. if (this.occlusionTexture) {
  46006. activeTextures.push(this.occlusionTexture);
  46007. }
  46008. if (this.lightmapTexture) {
  46009. activeTextures.push(this.lightmapTexture);
  46010. }
  46011. return activeTextures;
  46012. };
  46013. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46014. if (_super.prototype.hasTexture.call(this, texture)) {
  46015. return true;
  46016. }
  46017. if (this.lightmapTexture === texture) {
  46018. return true;
  46019. }
  46020. return false;
  46021. };
  46022. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46023. return "PBRBaseSimpleMaterial";
  46024. };
  46025. __decorate([
  46026. BABYLON.serialize(),
  46027. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46028. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46029. __decorate([
  46030. BABYLON.serialize(),
  46031. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46032. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46033. __decorate([
  46034. BABYLON.serializeAsTexture(),
  46035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46036. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46037. __decorate([
  46038. BABYLON.serialize(),
  46039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46040. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46041. __decorate([
  46042. BABYLON.serialize(),
  46043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46044. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46045. __decorate([
  46046. BABYLON.serializeAsTexture(),
  46047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46048. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46049. __decorate([
  46050. BABYLON.serializeAsColor3("emissive"),
  46051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46052. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46053. __decorate([
  46054. BABYLON.serializeAsTexture(),
  46055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46056. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46057. __decorate([
  46058. BABYLON.serialize(),
  46059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46060. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46061. __decorate([
  46062. BABYLON.serializeAsTexture(),
  46063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46064. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46065. __decorate([
  46066. BABYLON.serialize(),
  46067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46068. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46069. __decorate([
  46070. BABYLON.serialize()
  46071. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46072. __decorate([
  46073. BABYLON.serializeAsTexture(),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46075. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46076. __decorate([
  46077. BABYLON.serialize(),
  46078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46079. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46080. return PBRBaseSimpleMaterial;
  46081. }(BABYLON.PBRBaseMaterial));
  46082. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46083. })(BABYLON || (BABYLON = {}));
  46084. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46085. var BABYLON;
  46086. (function (BABYLON) {
  46087. /**
  46088. * The Physically based material of BJS.
  46089. *
  46090. * This offers the main features of a standard PBR material.
  46091. * For more information, please refer to the documentation :
  46092. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46093. */
  46094. var PBRMaterial = /** @class */ (function (_super) {
  46095. __extends(PBRMaterial, _super);
  46096. /**
  46097. * Instantiates a new PBRMaterial instance.
  46098. *
  46099. * @param name The material name
  46100. * @param scene The scene the material will be use in.
  46101. */
  46102. function PBRMaterial(name, scene) {
  46103. var _this = _super.call(this, name, scene) || this;
  46104. /**
  46105. * Intensity of the direct lights e.g. the four lights available in your scene.
  46106. * This impacts both the direct diffuse and specular highlights.
  46107. */
  46108. _this.directIntensity = 1.0;
  46109. /**
  46110. * Intensity of the emissive part of the material.
  46111. * This helps controlling the emissive effect without modifying the emissive color.
  46112. */
  46113. _this.emissiveIntensity = 1.0;
  46114. /**
  46115. * Intensity of the environment e.g. how much the environment will light the object
  46116. * either through harmonics for rough material or through the refelction for shiny ones.
  46117. */
  46118. _this.environmentIntensity = 1.0;
  46119. /**
  46120. * This is a special control allowing the reduction of the specular highlights coming from the
  46121. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46122. */
  46123. _this.specularIntensity = 1.0;
  46124. /**
  46125. * Debug Control allowing disabling the bump map on this material.
  46126. */
  46127. _this.disableBumpMap = false;
  46128. /**
  46129. * AKA Occlusion Texture Intensity in other nomenclature.
  46130. */
  46131. _this.ambientTextureStrength = 1.0;
  46132. /**
  46133. * The color of a material in ambient lighting.
  46134. */
  46135. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46136. /**
  46137. * AKA Diffuse Color in other nomenclature.
  46138. */
  46139. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46140. /**
  46141. * AKA Specular Color in other nomenclature.
  46142. */
  46143. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46144. /**
  46145. * The color reflected from the material.
  46146. */
  46147. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46148. /**
  46149. * The color emitted from the material.
  46150. */
  46151. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46152. /**
  46153. * AKA Glossiness in other nomenclature.
  46154. */
  46155. _this.microSurface = 1.0;
  46156. /**
  46157. * source material index of refraction (IOR)' / 'destination material IOR.
  46158. */
  46159. _this.indexOfRefraction = 0.66;
  46160. /**
  46161. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46162. */
  46163. _this.invertRefractionY = false;
  46164. /**
  46165. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46166. * Materials half opaque for instance using refraction could benefit from this control.
  46167. */
  46168. _this.linkRefractionWithTransparency = false;
  46169. _this.useLightmapAsShadowmap = false;
  46170. /**
  46171. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46172. */
  46173. _this.useAlphaFromAlbedoTexture = false;
  46174. /**
  46175. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46176. */
  46177. _this.forceAlphaTest = false;
  46178. /**
  46179. * Defines the alpha limits in alpha test mode.
  46180. */
  46181. _this.alphaCutOff = 0.4;
  46182. /**
  46183. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46184. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46185. */
  46186. _this.useSpecularOverAlpha = true;
  46187. /**
  46188. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46189. */
  46190. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46191. /**
  46192. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46193. */
  46194. _this.useRoughnessFromMetallicTextureAlpha = true;
  46195. /**
  46196. * Specifies if the metallic texture contains the roughness information in its green channel.
  46197. */
  46198. _this.useRoughnessFromMetallicTextureGreen = false;
  46199. /**
  46200. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46201. */
  46202. _this.useMetallnessFromMetallicTextureBlue = false;
  46203. /**
  46204. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46205. */
  46206. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46207. /**
  46208. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46209. */
  46210. _this.useAmbientInGrayScale = false;
  46211. /**
  46212. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46213. * The material will try to infer what glossiness each pixel should be.
  46214. */
  46215. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46216. /**
  46217. * BJS is using an harcoded light falloff based on a manually sets up range.
  46218. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46219. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46220. */
  46221. _this.usePhysicalLightFalloff = true;
  46222. /**
  46223. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46224. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46225. */
  46226. _this.useRadianceOverAlpha = true;
  46227. /**
  46228. * Allows using an object space normal map (instead of tangent space).
  46229. */
  46230. _this.useObjectSpaceNormalMap = false;
  46231. /**
  46232. * Allows using the bump map in parallax mode.
  46233. */
  46234. _this.useParallax = false;
  46235. /**
  46236. * Allows using the bump map in parallax occlusion mode.
  46237. */
  46238. _this.useParallaxOcclusion = false;
  46239. /**
  46240. * Controls the scale bias of the parallax mode.
  46241. */
  46242. _this.parallaxScaleBias = 0.05;
  46243. /**
  46244. * If sets to true, disables all the lights affecting the material.
  46245. */
  46246. _this.disableLighting = false;
  46247. /**
  46248. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46249. */
  46250. _this.forceIrradianceInFragment = false;
  46251. /**
  46252. * Number of Simultaneous lights allowed on the material.
  46253. */
  46254. _this.maxSimultaneousLights = 4;
  46255. /**
  46256. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46257. */
  46258. _this.invertNormalMapX = false;
  46259. /**
  46260. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46261. */
  46262. _this.invertNormalMapY = false;
  46263. /**
  46264. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46265. */
  46266. _this.twoSidedLighting = false;
  46267. /**
  46268. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46269. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46270. */
  46271. _this.useAlphaFresnel = false;
  46272. /**
  46273. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46274. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46275. */
  46276. _this.useLinearAlphaFresnel = false;
  46277. /**
  46278. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46279. * And/Or occlude the blended part.
  46280. */
  46281. _this.environmentBRDFTexture = null;
  46282. /**
  46283. * Force normal to face away from face.
  46284. */
  46285. _this.forceNormalForward = false;
  46286. /**
  46287. * Enables specular anti aliasing in the PBR shader.
  46288. * It will both interacts on the Geometry for analytical and IBL lighting.
  46289. * It also prefilter the roughness map based on the bump values.
  46290. */
  46291. _this.enableSpecularAntiAliasing = false;
  46292. /**
  46293. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46294. * makes the reflect vector face the model (under horizon).
  46295. */
  46296. _this.useHorizonOcclusion = true;
  46297. /**
  46298. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46299. * too much the area relying on ambient texture to define their ambient occlusion.
  46300. */
  46301. _this.useRadianceOcclusion = true;
  46302. /**
  46303. * If set to true, no lighting calculations will be applied.
  46304. */
  46305. _this.unlit = false;
  46306. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46307. return _this;
  46308. }
  46309. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46310. /**
  46311. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46312. */
  46313. get: function () {
  46314. return this._PBRMATERIAL_OPAQUE;
  46315. },
  46316. enumerable: true,
  46317. configurable: true
  46318. });
  46319. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46320. /**
  46321. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46322. */
  46323. get: function () {
  46324. return this._PBRMATERIAL_ALPHATEST;
  46325. },
  46326. enumerable: true,
  46327. configurable: true
  46328. });
  46329. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46330. /**
  46331. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46332. */
  46333. get: function () {
  46334. return this._PBRMATERIAL_ALPHABLEND;
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46340. /**
  46341. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46342. * They are also discarded below the alpha cutoff threshold to improve performances.
  46343. */
  46344. get: function () {
  46345. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46346. },
  46347. enumerable: true,
  46348. configurable: true
  46349. });
  46350. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46351. /**
  46352. * Gets the image processing configuration used either in this material.
  46353. */
  46354. get: function () {
  46355. return this._imageProcessingConfiguration;
  46356. },
  46357. /**
  46358. * Sets the Default image processing configuration used either in the this material.
  46359. *
  46360. * If sets to null, the scene one is in use.
  46361. */
  46362. set: function (value) {
  46363. this._attachImageProcessingConfiguration(value);
  46364. // Ensure the effect will be rebuilt.
  46365. this._markAllSubMeshesAsTexturesDirty();
  46366. },
  46367. enumerable: true,
  46368. configurable: true
  46369. });
  46370. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46371. /**
  46372. * Gets wether the color curves effect is enabled.
  46373. */
  46374. get: function () {
  46375. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46376. },
  46377. /**
  46378. * Sets wether the color curves effect is enabled.
  46379. */
  46380. set: function (value) {
  46381. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46382. },
  46383. enumerable: true,
  46384. configurable: true
  46385. });
  46386. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46387. /**
  46388. * Gets wether the color grading effect is enabled.
  46389. */
  46390. get: function () {
  46391. return this.imageProcessingConfiguration.colorGradingEnabled;
  46392. },
  46393. /**
  46394. * Gets wether the color grading effect is enabled.
  46395. */
  46396. set: function (value) {
  46397. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46398. },
  46399. enumerable: true,
  46400. configurable: true
  46401. });
  46402. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46403. /**
  46404. * Gets wether tonemapping is enabled or not.
  46405. */
  46406. get: function () {
  46407. return this._imageProcessingConfiguration.toneMappingEnabled;
  46408. },
  46409. /**
  46410. * Sets wether tonemapping is enabled or not
  46411. */
  46412. set: function (value) {
  46413. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46414. },
  46415. enumerable: true,
  46416. configurable: true
  46417. });
  46418. ;
  46419. ;
  46420. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46421. /**
  46422. * The camera exposure used on this material.
  46423. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46424. * This corresponds to a photographic exposure.
  46425. */
  46426. get: function () {
  46427. return this._imageProcessingConfiguration.exposure;
  46428. },
  46429. /**
  46430. * The camera exposure used on this material.
  46431. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46432. * This corresponds to a photographic exposure.
  46433. */
  46434. set: function (value) {
  46435. this._imageProcessingConfiguration.exposure = value;
  46436. },
  46437. enumerable: true,
  46438. configurable: true
  46439. });
  46440. ;
  46441. ;
  46442. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46443. /**
  46444. * Gets The camera contrast used on this material.
  46445. */
  46446. get: function () {
  46447. return this._imageProcessingConfiguration.contrast;
  46448. },
  46449. /**
  46450. * Sets The camera contrast used on this material.
  46451. */
  46452. set: function (value) {
  46453. this._imageProcessingConfiguration.contrast = value;
  46454. },
  46455. enumerable: true,
  46456. configurable: true
  46457. });
  46458. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46459. /**
  46460. * Gets the Color Grading 2D Lookup Texture.
  46461. */
  46462. get: function () {
  46463. return this._imageProcessingConfiguration.colorGradingTexture;
  46464. },
  46465. /**
  46466. * Sets the Color Grading 2D Lookup Texture.
  46467. */
  46468. set: function (value) {
  46469. this._imageProcessingConfiguration.colorGradingTexture = value;
  46470. },
  46471. enumerable: true,
  46472. configurable: true
  46473. });
  46474. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46475. /**
  46476. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46477. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46478. * 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;
  46479. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46480. */
  46481. get: function () {
  46482. return this._imageProcessingConfiguration.colorCurves;
  46483. },
  46484. /**
  46485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46487. * 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;
  46488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46489. */
  46490. set: function (value) {
  46491. this._imageProcessingConfiguration.colorCurves = value;
  46492. },
  46493. enumerable: true,
  46494. configurable: true
  46495. });
  46496. /**
  46497. * Returns the name of this material class.
  46498. */
  46499. PBRMaterial.prototype.getClassName = function () {
  46500. return "PBRMaterial";
  46501. };
  46502. /**
  46503. * Returns an array of the actively used textures.
  46504. * @returns - Array of BaseTextures
  46505. */
  46506. PBRMaterial.prototype.getActiveTextures = function () {
  46507. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46508. if (this._albedoTexture) {
  46509. activeTextures.push(this._albedoTexture);
  46510. }
  46511. if (this._ambientTexture) {
  46512. activeTextures.push(this._ambientTexture);
  46513. }
  46514. if (this._opacityTexture) {
  46515. activeTextures.push(this._opacityTexture);
  46516. }
  46517. if (this._reflectionTexture) {
  46518. activeTextures.push(this._reflectionTexture);
  46519. }
  46520. if (this._emissiveTexture) {
  46521. activeTextures.push(this._emissiveTexture);
  46522. }
  46523. if (this._reflectivityTexture) {
  46524. activeTextures.push(this._reflectivityTexture);
  46525. }
  46526. if (this._metallicTexture) {
  46527. activeTextures.push(this._metallicTexture);
  46528. }
  46529. if (this._microSurfaceTexture) {
  46530. activeTextures.push(this._microSurfaceTexture);
  46531. }
  46532. if (this._bumpTexture) {
  46533. activeTextures.push(this._bumpTexture);
  46534. }
  46535. if (this._lightmapTexture) {
  46536. activeTextures.push(this._lightmapTexture);
  46537. }
  46538. if (this._refractionTexture) {
  46539. activeTextures.push(this._refractionTexture);
  46540. }
  46541. return activeTextures;
  46542. };
  46543. /**
  46544. * Checks to see if a texture is used in the material.
  46545. * @param texture - Base texture to use.
  46546. * @returns - Boolean specifying if a texture is used in the material.
  46547. */
  46548. PBRMaterial.prototype.hasTexture = function (texture) {
  46549. if (_super.prototype.hasTexture.call(this, texture)) {
  46550. return true;
  46551. }
  46552. if (this._albedoTexture === texture) {
  46553. return true;
  46554. }
  46555. if (this._ambientTexture === texture) {
  46556. return true;
  46557. }
  46558. if (this._opacityTexture === texture) {
  46559. return true;
  46560. }
  46561. if (this._reflectionTexture === texture) {
  46562. return true;
  46563. }
  46564. if (this._reflectivityTexture === texture) {
  46565. return true;
  46566. }
  46567. if (this._metallicTexture === texture) {
  46568. return true;
  46569. }
  46570. if (this._microSurfaceTexture === texture) {
  46571. return true;
  46572. }
  46573. if (this._bumpTexture === texture) {
  46574. return true;
  46575. }
  46576. if (this._lightmapTexture === texture) {
  46577. return true;
  46578. }
  46579. if (this._refractionTexture === texture) {
  46580. return true;
  46581. }
  46582. return false;
  46583. };
  46584. /**
  46585. * Makes a duplicate of the current material.
  46586. * @param name - name to use for the new material.
  46587. */
  46588. PBRMaterial.prototype.clone = function (name) {
  46589. var _this = this;
  46590. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46591. clone.id = name;
  46592. clone.name = name;
  46593. return clone;
  46594. };
  46595. /**
  46596. * Serializes this PBR Material.
  46597. * @returns - An object with the serialized material.
  46598. */
  46599. PBRMaterial.prototype.serialize = function () {
  46600. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46601. serializationObject.customType = "BABYLON.PBRMaterial";
  46602. return serializationObject;
  46603. };
  46604. // Statics
  46605. /**
  46606. * Parses a PBR Material from a serialized object.
  46607. * @param source - Serialized object.
  46608. * @param scene - BJS scene instance.
  46609. * @param rootUrl - url for the scene object
  46610. * @returns - PBRMaterial
  46611. */
  46612. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46613. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46614. };
  46615. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46616. /**
  46617. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46618. */
  46619. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46620. /**
  46621. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46622. */
  46623. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46624. /**
  46625. * 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.
  46626. * They are also discarded below the alpha cutoff threshold to improve performances.
  46627. */
  46628. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46629. __decorate([
  46630. BABYLON.serialize(),
  46631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46632. ], PBRMaterial.prototype, "directIntensity", void 0);
  46633. __decorate([
  46634. BABYLON.serialize(),
  46635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46636. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46637. __decorate([
  46638. BABYLON.serialize(),
  46639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46640. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46641. __decorate([
  46642. BABYLON.serialize(),
  46643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46644. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46645. __decorate([
  46646. BABYLON.serialize(),
  46647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46648. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46649. __decorate([
  46650. BABYLON.serializeAsTexture(),
  46651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46652. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46653. __decorate([
  46654. BABYLON.serializeAsTexture(),
  46655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46656. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46657. __decorate([
  46658. BABYLON.serialize(),
  46659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46660. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46661. __decorate([
  46662. BABYLON.serializeAsTexture(),
  46663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46664. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46665. __decorate([
  46666. BABYLON.serializeAsTexture(),
  46667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46668. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46669. __decorate([
  46670. BABYLON.serializeAsTexture(),
  46671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46672. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46673. __decorate([
  46674. BABYLON.serializeAsTexture(),
  46675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46676. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46677. __decorate([
  46678. BABYLON.serializeAsTexture(),
  46679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46680. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46681. __decorate([
  46682. BABYLON.serialize(),
  46683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46684. ], PBRMaterial.prototype, "metallic", void 0);
  46685. __decorate([
  46686. BABYLON.serialize(),
  46687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46688. ], PBRMaterial.prototype, "roughness", void 0);
  46689. __decorate([
  46690. BABYLON.serializeAsTexture(),
  46691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46692. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46693. __decorate([
  46694. BABYLON.serializeAsTexture(),
  46695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46696. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46697. __decorate([
  46698. BABYLON.serializeAsTexture(),
  46699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46700. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46701. __decorate([
  46702. BABYLON.serializeAsTexture(),
  46703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46704. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46705. __decorate([
  46706. BABYLON.serializeAsColor3("ambient"),
  46707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46708. ], PBRMaterial.prototype, "ambientColor", void 0);
  46709. __decorate([
  46710. BABYLON.serializeAsColor3("albedo"),
  46711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46712. ], PBRMaterial.prototype, "albedoColor", void 0);
  46713. __decorate([
  46714. BABYLON.serializeAsColor3("reflectivity"),
  46715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46716. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46717. __decorate([
  46718. BABYLON.serializeAsColor3("reflection"),
  46719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46720. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46721. __decorate([
  46722. BABYLON.serializeAsColor3("emissive"),
  46723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46724. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46725. __decorate([
  46726. BABYLON.serialize(),
  46727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46728. ], PBRMaterial.prototype, "microSurface", void 0);
  46729. __decorate([
  46730. BABYLON.serialize(),
  46731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46732. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46733. __decorate([
  46734. BABYLON.serialize(),
  46735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46736. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46737. __decorate([
  46738. BABYLON.serialize(),
  46739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46740. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46741. __decorate([
  46742. BABYLON.serialize(),
  46743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46744. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46745. __decorate([
  46746. BABYLON.serialize(),
  46747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46748. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46749. __decorate([
  46750. BABYLON.serialize(),
  46751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46752. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46753. __decorate([
  46754. BABYLON.serialize(),
  46755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46756. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46757. __decorate([
  46758. BABYLON.serialize(),
  46759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46760. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46761. __decorate([
  46762. BABYLON.serialize(),
  46763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46764. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46765. __decorate([
  46766. BABYLON.serialize(),
  46767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46768. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46769. __decorate([
  46770. BABYLON.serialize(),
  46771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46772. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46773. __decorate([
  46774. BABYLON.serialize(),
  46775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46776. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46777. __decorate([
  46778. BABYLON.serialize(),
  46779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46780. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46781. __decorate([
  46782. BABYLON.serialize(),
  46783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46784. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46785. __decorate([
  46786. BABYLON.serialize(),
  46787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46788. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46789. __decorate([
  46790. BABYLON.serialize(),
  46791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46792. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46793. __decorate([
  46794. BABYLON.serialize(),
  46795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46796. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46797. __decorate([
  46798. BABYLON.serialize(),
  46799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46800. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46801. __decorate([
  46802. BABYLON.serialize(),
  46803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46804. ], PBRMaterial.prototype, "useParallax", void 0);
  46805. __decorate([
  46806. BABYLON.serialize(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46808. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46809. __decorate([
  46810. BABYLON.serialize(),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46812. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46813. __decorate([
  46814. BABYLON.serialize(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46816. ], PBRMaterial.prototype, "disableLighting", void 0);
  46817. __decorate([
  46818. BABYLON.serialize(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46820. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46821. __decorate([
  46822. BABYLON.serialize(),
  46823. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46824. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46825. __decorate([
  46826. BABYLON.serialize(),
  46827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46828. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46829. __decorate([
  46830. BABYLON.serialize(),
  46831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46832. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46833. __decorate([
  46834. BABYLON.serialize(),
  46835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46836. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46837. __decorate([
  46838. BABYLON.serialize(),
  46839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46840. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46841. __decorate([
  46842. BABYLON.serialize(),
  46843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46844. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46845. __decorate([
  46846. BABYLON.serializeAsTexture(),
  46847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46848. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46849. __decorate([
  46850. BABYLON.serialize(),
  46851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46852. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46853. __decorate([
  46854. BABYLON.serialize(),
  46855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46856. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46857. __decorate([
  46858. BABYLON.serialize(),
  46859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46860. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46861. __decorate([
  46862. BABYLON.serialize(),
  46863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46864. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46865. __decorate([
  46866. BABYLON.serialize(),
  46867. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46868. ], PBRMaterial.prototype, "unlit", void 0);
  46869. return PBRMaterial;
  46870. }(BABYLON.PBRBaseMaterial));
  46871. BABYLON.PBRMaterial = PBRMaterial;
  46872. })(BABYLON || (BABYLON = {}));
  46873. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46874. var BABYLON;
  46875. (function (BABYLON) {
  46876. /**
  46877. * The PBR material of BJS following the metal roughness convention.
  46878. *
  46879. * This fits to the PBR convention in the GLTF definition:
  46880. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46881. */
  46882. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46883. __extends(PBRMetallicRoughnessMaterial, _super);
  46884. /**
  46885. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46886. *
  46887. * @param name The material name
  46888. * @param scene The scene the material will be use in.
  46889. */
  46890. function PBRMetallicRoughnessMaterial(name, scene) {
  46891. var _this = _super.call(this, name, scene) || this;
  46892. _this._useRoughnessFromMetallicTextureAlpha = false;
  46893. _this._useRoughnessFromMetallicTextureGreen = true;
  46894. _this._useMetallnessFromMetallicTextureBlue = true;
  46895. _this.metallic = 1.0;
  46896. _this.roughness = 1.0;
  46897. return _this;
  46898. }
  46899. /**
  46900. * Return the currrent class name of the material.
  46901. */
  46902. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46903. return "PBRMetallicRoughnessMaterial";
  46904. };
  46905. /**
  46906. * Return the active textures of the material.
  46907. */
  46908. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46909. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46910. if (this.baseTexture) {
  46911. activeTextures.push(this.baseTexture);
  46912. }
  46913. if (this.metallicRoughnessTexture) {
  46914. activeTextures.push(this.metallicRoughnessTexture);
  46915. }
  46916. return activeTextures;
  46917. };
  46918. /**
  46919. * Checks to see if a texture is used in the material.
  46920. * @param texture - Base texture to use.
  46921. * @returns - Boolean specifying if a texture is used in the material.
  46922. */
  46923. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46924. if (_super.prototype.hasTexture.call(this, texture)) {
  46925. return true;
  46926. }
  46927. if (this.baseTexture === texture) {
  46928. return true;
  46929. }
  46930. if (this.metallicRoughnessTexture === texture) {
  46931. return true;
  46932. }
  46933. return false;
  46934. };
  46935. /**
  46936. * Makes a duplicate of the current material.
  46937. * @param name - name to use for the new material.
  46938. */
  46939. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46940. var _this = this;
  46941. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46942. clone.id = name;
  46943. clone.name = name;
  46944. return clone;
  46945. };
  46946. /**
  46947. * Serialize the material to a parsable JSON object.
  46948. */
  46949. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46950. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46951. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46952. return serializationObject;
  46953. };
  46954. /**
  46955. * Parses a JSON object correponding to the serialize function.
  46956. */
  46957. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46958. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46959. };
  46960. __decorate([
  46961. BABYLON.serializeAsColor3(),
  46962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46963. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46964. __decorate([
  46965. BABYLON.serializeAsTexture(),
  46966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46967. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46968. __decorate([
  46969. BABYLON.serialize(),
  46970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46971. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46972. __decorate([
  46973. BABYLON.serialize(),
  46974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46975. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46976. __decorate([
  46977. BABYLON.serializeAsTexture(),
  46978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46979. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46980. return PBRMetallicRoughnessMaterial;
  46981. }(BABYLON.PBRBaseSimpleMaterial));
  46982. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46983. })(BABYLON || (BABYLON = {}));
  46984. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46985. var BABYLON;
  46986. (function (BABYLON) {
  46987. /**
  46988. * The PBR material of BJS following the specular glossiness convention.
  46989. *
  46990. * This fits to the PBR convention in the GLTF definition:
  46991. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46992. */
  46993. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46994. __extends(PBRSpecularGlossinessMaterial, _super);
  46995. /**
  46996. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46997. *
  46998. * @param name The material name
  46999. * @param scene The scene the material will be use in.
  47000. */
  47001. function PBRSpecularGlossinessMaterial(name, scene) {
  47002. var _this = _super.call(this, name, scene) || this;
  47003. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47004. return _this;
  47005. }
  47006. /**
  47007. * Return the currrent class name of the material.
  47008. */
  47009. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47010. return "PBRSpecularGlossinessMaterial";
  47011. };
  47012. /**
  47013. * Return the active textures of the material.
  47014. */
  47015. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47016. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47017. if (this.diffuseTexture) {
  47018. activeTextures.push(this.diffuseTexture);
  47019. }
  47020. if (this.specularGlossinessTexture) {
  47021. activeTextures.push(this.specularGlossinessTexture);
  47022. }
  47023. return activeTextures;
  47024. };
  47025. /**
  47026. * Checks to see if a texture is used in the material.
  47027. * @param texture - Base texture to use.
  47028. * @returns - Boolean specifying if a texture is used in the material.
  47029. */
  47030. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47031. if (_super.prototype.hasTexture.call(this, texture)) {
  47032. return true;
  47033. }
  47034. if (this.diffuseTexture === texture) {
  47035. return true;
  47036. }
  47037. if (this.specularGlossinessTexture === texture) {
  47038. return true;
  47039. }
  47040. return false;
  47041. };
  47042. /**
  47043. * Makes a duplicate of the current material.
  47044. * @param name - name to use for the new material.
  47045. */
  47046. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47047. var _this = this;
  47048. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47049. clone.id = name;
  47050. clone.name = name;
  47051. return clone;
  47052. };
  47053. /**
  47054. * Serialize the material to a parsable JSON object.
  47055. */
  47056. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47057. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47058. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47059. return serializationObject;
  47060. };
  47061. /**
  47062. * Parses a JSON object correponding to the serialize function.
  47063. */
  47064. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47065. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47066. };
  47067. __decorate([
  47068. BABYLON.serializeAsColor3("diffuse"),
  47069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47070. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47071. __decorate([
  47072. BABYLON.serializeAsTexture(),
  47073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47074. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47075. __decorate([
  47076. BABYLON.serializeAsColor3("specular"),
  47077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47078. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47079. __decorate([
  47080. BABYLON.serialize(),
  47081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47082. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47083. __decorate([
  47084. BABYLON.serializeAsTexture(),
  47085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47086. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47087. return PBRSpecularGlossinessMaterial;
  47088. }(BABYLON.PBRBaseSimpleMaterial));
  47089. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47090. })(BABYLON || (BABYLON = {}));
  47091. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47092. var BABYLON;
  47093. (function (BABYLON) {
  47094. BABYLON.CameraInputTypes = {};
  47095. var CameraInputsManager = /** @class */ (function () {
  47096. function CameraInputsManager(camera) {
  47097. this.attached = {};
  47098. this.camera = camera;
  47099. this.checkInputs = function () { };
  47100. }
  47101. /**
  47102. * Add an input method to a camera.
  47103. * builtin inputs example: camera.inputs.addGamepad();
  47104. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47105. * @param input camera input method
  47106. */
  47107. CameraInputsManager.prototype.add = function (input) {
  47108. var type = input.getSimpleName();
  47109. if (this.attached[type]) {
  47110. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47111. return;
  47112. }
  47113. this.attached[type] = input;
  47114. input.camera = this.camera;
  47115. //for checkInputs, we are dynamically creating a function
  47116. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47117. if (input.checkInputs) {
  47118. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47119. }
  47120. if (this.attachedElement) {
  47121. input.attachControl(this.attachedElement);
  47122. }
  47123. };
  47124. /**
  47125. * Remove a specific input method from a camera
  47126. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47127. * @param inputToRemove camera input method
  47128. */
  47129. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47130. for (var cam in this.attached) {
  47131. var input = this.attached[cam];
  47132. if (input === inputToRemove) {
  47133. input.detachControl(this.attachedElement);
  47134. input.camera = null;
  47135. delete this.attached[cam];
  47136. this.rebuildInputCheck();
  47137. }
  47138. }
  47139. };
  47140. CameraInputsManager.prototype.removeByType = function (inputType) {
  47141. for (var cam in this.attached) {
  47142. var input = this.attached[cam];
  47143. if (input.getClassName() === inputType) {
  47144. input.detachControl(this.attachedElement);
  47145. input.camera = null;
  47146. delete this.attached[cam];
  47147. this.rebuildInputCheck();
  47148. }
  47149. }
  47150. };
  47151. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47152. var current = this.checkInputs;
  47153. return function () {
  47154. current();
  47155. fn();
  47156. };
  47157. };
  47158. CameraInputsManager.prototype.attachInput = function (input) {
  47159. if (this.attachedElement) {
  47160. input.attachControl(this.attachedElement, this.noPreventDefault);
  47161. }
  47162. };
  47163. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47164. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47165. if (this.attachedElement) {
  47166. return;
  47167. }
  47168. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47169. this.attachedElement = element;
  47170. this.noPreventDefault = noPreventDefault;
  47171. for (var cam in this.attached) {
  47172. this.attached[cam].attachControl(element, noPreventDefault);
  47173. }
  47174. };
  47175. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47176. if (disconnect === void 0) { disconnect = false; }
  47177. if (this.attachedElement !== element) {
  47178. return;
  47179. }
  47180. for (var cam in this.attached) {
  47181. this.attached[cam].detachControl(element);
  47182. if (disconnect) {
  47183. this.attached[cam].camera = null;
  47184. }
  47185. }
  47186. this.attachedElement = null;
  47187. };
  47188. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47189. this.checkInputs = function () { };
  47190. for (var cam in this.attached) {
  47191. var input = this.attached[cam];
  47192. if (input.checkInputs) {
  47193. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47194. }
  47195. }
  47196. };
  47197. /**
  47198. * Remove all attached input methods from a camera
  47199. */
  47200. CameraInputsManager.prototype.clear = function () {
  47201. if (this.attachedElement) {
  47202. this.detachElement(this.attachedElement, true);
  47203. }
  47204. this.attached = {};
  47205. this.attachedElement = null;
  47206. this.checkInputs = function () { };
  47207. };
  47208. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47209. var inputs = {};
  47210. for (var cam in this.attached) {
  47211. var input = this.attached[cam];
  47212. var res = BABYLON.SerializationHelper.Serialize(input);
  47213. inputs[input.getClassName()] = res;
  47214. }
  47215. serializedCamera.inputsmgr = inputs;
  47216. };
  47217. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47218. var parsedInputs = parsedCamera.inputsmgr;
  47219. if (parsedInputs) {
  47220. this.clear();
  47221. for (var n in parsedInputs) {
  47222. var construct = BABYLON.CameraInputTypes[n];
  47223. if (construct) {
  47224. var parsedinput = parsedInputs[n];
  47225. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47226. this.add(input);
  47227. }
  47228. }
  47229. }
  47230. else {
  47231. //2016-03-08 this part is for managing backward compatibility
  47232. for (var n in this.attached) {
  47233. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47234. if (construct) {
  47235. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47236. this.remove(this.attached[n]);
  47237. this.add(input);
  47238. }
  47239. }
  47240. }
  47241. };
  47242. return CameraInputsManager;
  47243. }());
  47244. BABYLON.CameraInputsManager = CameraInputsManager;
  47245. })(BABYLON || (BABYLON = {}));
  47246. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47247. var BABYLON;
  47248. (function (BABYLON) {
  47249. var TargetCamera = /** @class */ (function (_super) {
  47250. __extends(TargetCamera, _super);
  47251. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47252. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47253. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47254. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47255. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47256. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47257. _this.speed = 2.0;
  47258. _this.noRotationConstraint = false;
  47259. _this.lockedTarget = null;
  47260. _this._currentTarget = BABYLON.Vector3.Zero();
  47261. _this._viewMatrix = BABYLON.Matrix.Zero();
  47262. _this._camMatrix = BABYLON.Matrix.Zero();
  47263. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47264. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47265. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47266. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47267. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47268. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47269. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47270. return _this;
  47271. }
  47272. TargetCamera.prototype.getFrontPosition = function (distance) {
  47273. this.getWorldMatrix();
  47274. var direction = this.getTarget().subtract(this.position);
  47275. direction.normalize();
  47276. direction.scaleInPlace(distance);
  47277. return this.globalPosition.add(direction);
  47278. };
  47279. TargetCamera.prototype._getLockedTargetPosition = function () {
  47280. if (!this.lockedTarget) {
  47281. return null;
  47282. }
  47283. if (this.lockedTarget.absolutePosition) {
  47284. this.lockedTarget.computeWorldMatrix();
  47285. }
  47286. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47287. };
  47288. TargetCamera.prototype.storeState = function () {
  47289. this._storedPosition = this.position.clone();
  47290. this._storedRotation = this.rotation.clone();
  47291. if (this.rotationQuaternion) {
  47292. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47293. }
  47294. return _super.prototype.storeState.call(this);
  47295. };
  47296. /**
  47297. * Restored camera state. You must call storeState() first
  47298. */
  47299. TargetCamera.prototype._restoreStateValues = function () {
  47300. if (!_super.prototype._restoreStateValues.call(this)) {
  47301. return false;
  47302. }
  47303. this.position = this._storedPosition.clone();
  47304. this.rotation = this._storedRotation.clone();
  47305. if (this.rotationQuaternion) {
  47306. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47307. }
  47308. this.cameraDirection.copyFromFloats(0, 0, 0);
  47309. this.cameraRotation.copyFromFloats(0, 0);
  47310. return true;
  47311. };
  47312. // Cache
  47313. TargetCamera.prototype._initCache = function () {
  47314. _super.prototype._initCache.call(this);
  47315. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47316. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47317. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47318. };
  47319. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47320. if (!ignoreParentClass) {
  47321. _super.prototype._updateCache.call(this);
  47322. }
  47323. var lockedTargetPosition = this._getLockedTargetPosition();
  47324. if (!lockedTargetPosition) {
  47325. this._cache.lockedTarget = null;
  47326. }
  47327. else {
  47328. if (!this._cache.lockedTarget) {
  47329. this._cache.lockedTarget = lockedTargetPosition.clone();
  47330. }
  47331. else {
  47332. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47333. }
  47334. }
  47335. this._cache.rotation.copyFrom(this.rotation);
  47336. if (this.rotationQuaternion)
  47337. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47338. };
  47339. // Synchronized
  47340. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47341. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47342. return false;
  47343. }
  47344. var lockedTargetPosition = this._getLockedTargetPosition();
  47345. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47346. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47347. };
  47348. // Methods
  47349. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47350. var engine = this.getEngine();
  47351. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47352. };
  47353. // Target
  47354. TargetCamera.prototype.setTarget = function (target) {
  47355. this.upVector.normalize();
  47356. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47357. this._camMatrix.invert();
  47358. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47359. var vDir = target.subtract(this.position);
  47360. if (vDir.x >= 0.0) {
  47361. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47362. }
  47363. else {
  47364. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47365. }
  47366. this.rotation.z = 0;
  47367. if (isNaN(this.rotation.x)) {
  47368. this.rotation.x = 0;
  47369. }
  47370. if (isNaN(this.rotation.y)) {
  47371. this.rotation.y = 0;
  47372. }
  47373. if (isNaN(this.rotation.z)) {
  47374. this.rotation.z = 0;
  47375. }
  47376. if (this.rotationQuaternion) {
  47377. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47378. }
  47379. };
  47380. /**
  47381. * Return the current target position of the camera. This value is expressed in local space.
  47382. */
  47383. TargetCamera.prototype.getTarget = function () {
  47384. return this._currentTarget;
  47385. };
  47386. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47387. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47388. };
  47389. TargetCamera.prototype._updatePosition = function () {
  47390. if (this.parent) {
  47391. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47392. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47393. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47394. return;
  47395. }
  47396. this.position.addInPlace(this.cameraDirection);
  47397. };
  47398. TargetCamera.prototype._checkInputs = function () {
  47399. var needToMove = this._decideIfNeedsToMove();
  47400. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47401. // Move
  47402. if (needToMove) {
  47403. this._updatePosition();
  47404. }
  47405. // Rotate
  47406. if (needToRotate) {
  47407. this.rotation.x += this.cameraRotation.x;
  47408. this.rotation.y += this.cameraRotation.y;
  47409. //rotate, if quaternion is set and rotation was used
  47410. if (this.rotationQuaternion) {
  47411. var len = this.rotation.lengthSquared();
  47412. if (len) {
  47413. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47414. }
  47415. }
  47416. if (!this.noRotationConstraint) {
  47417. var limit = (Math.PI / 2) * 0.95;
  47418. if (this.rotation.x > limit)
  47419. this.rotation.x = limit;
  47420. if (this.rotation.x < -limit)
  47421. this.rotation.x = -limit;
  47422. }
  47423. }
  47424. // Inertia
  47425. if (needToMove) {
  47426. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47427. this.cameraDirection.x = 0;
  47428. }
  47429. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47430. this.cameraDirection.y = 0;
  47431. }
  47432. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47433. this.cameraDirection.z = 0;
  47434. }
  47435. this.cameraDirection.scaleInPlace(this.inertia);
  47436. }
  47437. if (needToRotate) {
  47438. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47439. this.cameraRotation.x = 0;
  47440. }
  47441. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47442. this.cameraRotation.y = 0;
  47443. }
  47444. this.cameraRotation.scaleInPlace(this.inertia);
  47445. }
  47446. _super.prototype._checkInputs.call(this);
  47447. };
  47448. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47449. if (this.rotationQuaternion) {
  47450. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47451. }
  47452. else {
  47453. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47454. }
  47455. //update the up vector!
  47456. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47457. };
  47458. TargetCamera.prototype._getViewMatrix = function () {
  47459. if (this.lockedTarget) {
  47460. this.setTarget(this._getLockedTargetPosition());
  47461. }
  47462. // Compute
  47463. this._updateCameraRotationMatrix();
  47464. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47465. // Computing target and final matrix
  47466. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47467. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47468. return this._viewMatrix;
  47469. };
  47470. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47471. if (this.parent) {
  47472. var parentWorldMatrix = this.parent.getWorldMatrix();
  47473. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47474. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47475. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47476. this._markSyncedWithParent();
  47477. }
  47478. else {
  47479. this._globalPosition.copyFrom(this.position);
  47480. this._globalCurrentTarget.copyFrom(target);
  47481. this._globalCurrentUpVector.copyFrom(up);
  47482. }
  47483. if (this.getScene().useRightHandedSystem) {
  47484. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47485. }
  47486. else {
  47487. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47488. }
  47489. };
  47490. /**
  47491. * @override
  47492. * Override Camera.createRigCamera
  47493. */
  47494. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47495. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47496. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47497. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47498. if (!this.rotationQuaternion) {
  47499. this.rotationQuaternion = new BABYLON.Quaternion();
  47500. }
  47501. rigCamera._cameraRigParams = {};
  47502. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47503. }
  47504. return rigCamera;
  47505. }
  47506. return null;
  47507. };
  47508. /**
  47509. * @override
  47510. * Override Camera._updateRigCameras
  47511. */
  47512. TargetCamera.prototype._updateRigCameras = function () {
  47513. var camLeft = this._rigCameras[0];
  47514. var camRight = this._rigCameras[1];
  47515. switch (this.cameraRigMode) {
  47516. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47517. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47518. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47520. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47521. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47522. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47523. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47524. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47525. camLeft.setTarget(this.getTarget());
  47526. camRight.setTarget(this.getTarget());
  47527. break;
  47528. case BABYLON.Camera.RIG_MODE_VR:
  47529. if (camLeft.rotationQuaternion) {
  47530. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47531. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47532. }
  47533. else {
  47534. camLeft.rotation.copyFrom(this.rotation);
  47535. camRight.rotation.copyFrom(this.rotation);
  47536. }
  47537. camLeft.position.copyFrom(this.position);
  47538. camRight.position.copyFrom(this.position);
  47539. break;
  47540. }
  47541. _super.prototype._updateRigCameras.call(this);
  47542. };
  47543. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47544. if (!this._rigCamTransformMatrix) {
  47545. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47546. }
  47547. var target = this.getTarget();
  47548. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47549. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47550. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47551. };
  47552. TargetCamera.prototype.getClassName = function () {
  47553. return "TargetCamera";
  47554. };
  47555. __decorate([
  47556. BABYLON.serializeAsVector3()
  47557. ], TargetCamera.prototype, "rotation", void 0);
  47558. __decorate([
  47559. BABYLON.serialize()
  47560. ], TargetCamera.prototype, "speed", void 0);
  47561. __decorate([
  47562. BABYLON.serializeAsMeshReference("lockedTargetId")
  47563. ], TargetCamera.prototype, "lockedTarget", void 0);
  47564. return TargetCamera;
  47565. }(BABYLON.Camera));
  47566. BABYLON.TargetCamera = TargetCamera;
  47567. })(BABYLON || (BABYLON = {}));
  47568. //# sourceMappingURL=babylon.targetCamera.js.map
  47569. var BABYLON;
  47570. (function (BABYLON) {
  47571. var FreeCameraMouseInput = /** @class */ (function () {
  47572. function FreeCameraMouseInput(touchEnabled) {
  47573. if (touchEnabled === void 0) { touchEnabled = true; }
  47574. this.touchEnabled = touchEnabled;
  47575. this.buttons = [0, 1, 2];
  47576. this.angularSensibility = 2000.0;
  47577. this.previousPosition = null;
  47578. }
  47579. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47580. var _this = this;
  47581. var engine = this.camera.getEngine();
  47582. if (!this._pointerInput) {
  47583. this._pointerInput = function (p, s) {
  47584. var evt = p.event;
  47585. if (engine.isInVRExclusivePointerMode) {
  47586. return;
  47587. }
  47588. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47589. return;
  47590. }
  47591. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47592. return;
  47593. }
  47594. var srcElement = (evt.srcElement || evt.target);
  47595. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47596. try {
  47597. srcElement.setPointerCapture(evt.pointerId);
  47598. }
  47599. catch (e) {
  47600. //Nothing to do with the error. Execution will continue.
  47601. }
  47602. _this.previousPosition = {
  47603. x: evt.clientX,
  47604. y: evt.clientY
  47605. };
  47606. if (!noPreventDefault) {
  47607. evt.preventDefault();
  47608. element.focus();
  47609. }
  47610. }
  47611. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47612. try {
  47613. srcElement.releasePointerCapture(evt.pointerId);
  47614. }
  47615. catch (e) {
  47616. //Nothing to do with the error.
  47617. }
  47618. _this.previousPosition = null;
  47619. if (!noPreventDefault) {
  47620. evt.preventDefault();
  47621. }
  47622. }
  47623. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47624. if (!_this.previousPosition || engine.isPointerLock) {
  47625. return;
  47626. }
  47627. var offsetX = evt.clientX - _this.previousPosition.x;
  47628. if (_this.camera.getScene().useRightHandedSystem)
  47629. offsetX *= -1;
  47630. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47631. offsetX *= -1;
  47632. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47633. var offsetY = evt.clientY - _this.previousPosition.y;
  47634. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47635. _this.previousPosition = {
  47636. x: evt.clientX,
  47637. y: evt.clientY
  47638. };
  47639. if (!noPreventDefault) {
  47640. evt.preventDefault();
  47641. }
  47642. }
  47643. };
  47644. }
  47645. this._onMouseMove = function (evt) {
  47646. if (!engine.isPointerLock) {
  47647. return;
  47648. }
  47649. if (engine.isInVRExclusivePointerMode) {
  47650. return;
  47651. }
  47652. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47653. if (_this.camera.getScene().useRightHandedSystem)
  47654. offsetX *= -1;
  47655. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47656. offsetX *= -1;
  47657. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47658. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47659. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47660. _this.previousPosition = null;
  47661. if (!noPreventDefault) {
  47662. evt.preventDefault();
  47663. }
  47664. };
  47665. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47666. element.addEventListener("mousemove", this._onMouseMove, false);
  47667. };
  47668. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47669. if (this._observer && element) {
  47670. this.camera.getScene().onPointerObservable.remove(this._observer);
  47671. if (this._onMouseMove) {
  47672. element.removeEventListener("mousemove", this._onMouseMove);
  47673. }
  47674. this._observer = null;
  47675. this._onMouseMove = null;
  47676. this.previousPosition = null;
  47677. }
  47678. };
  47679. FreeCameraMouseInput.prototype.getClassName = function () {
  47680. return "FreeCameraMouseInput";
  47681. };
  47682. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47683. return "mouse";
  47684. };
  47685. __decorate([
  47686. BABYLON.serialize()
  47687. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47688. __decorate([
  47689. BABYLON.serialize()
  47690. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47691. return FreeCameraMouseInput;
  47692. }());
  47693. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47694. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47695. })(BABYLON || (BABYLON = {}));
  47696. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47697. var BABYLON;
  47698. (function (BABYLON) {
  47699. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47700. function FreeCameraKeyboardMoveInput() {
  47701. this._keys = new Array();
  47702. this.keysUp = [38];
  47703. this.keysDown = [40];
  47704. this.keysLeft = [37];
  47705. this.keysRight = [39];
  47706. }
  47707. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47708. var _this = this;
  47709. if (this._onCanvasBlurObserver) {
  47710. return;
  47711. }
  47712. this._scene = this.camera.getScene();
  47713. this._engine = this._scene.getEngine();
  47714. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47715. _this._keys = [];
  47716. });
  47717. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47718. var evt = info.event;
  47719. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47720. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47721. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47722. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47723. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47724. var index = _this._keys.indexOf(evt.keyCode);
  47725. if (index === -1) {
  47726. _this._keys.push(evt.keyCode);
  47727. }
  47728. if (!noPreventDefault) {
  47729. evt.preventDefault();
  47730. }
  47731. }
  47732. }
  47733. else {
  47734. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47735. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47736. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47737. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47738. var index = _this._keys.indexOf(evt.keyCode);
  47739. if (index >= 0) {
  47740. _this._keys.splice(index, 1);
  47741. }
  47742. if (!noPreventDefault) {
  47743. evt.preventDefault();
  47744. }
  47745. }
  47746. }
  47747. });
  47748. };
  47749. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47750. if (this._scene) {
  47751. if (this._onKeyboardObserver) {
  47752. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47753. }
  47754. if (this._onCanvasBlurObserver) {
  47755. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47756. }
  47757. this._onKeyboardObserver = null;
  47758. this._onCanvasBlurObserver = null;
  47759. }
  47760. this._keys = [];
  47761. };
  47762. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47763. if (this._onKeyboardObserver) {
  47764. var camera = this.camera;
  47765. // Keyboard
  47766. for (var index = 0; index < this._keys.length; index++) {
  47767. var keyCode = this._keys[index];
  47768. var speed = camera._computeLocalCameraSpeed();
  47769. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47770. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47771. }
  47772. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47773. camera._localDirection.copyFromFloats(0, 0, speed);
  47774. }
  47775. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47776. camera._localDirection.copyFromFloats(speed, 0, 0);
  47777. }
  47778. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47779. camera._localDirection.copyFromFloats(0, 0, -speed);
  47780. }
  47781. if (camera.getScene().useRightHandedSystem) {
  47782. camera._localDirection.z *= -1;
  47783. }
  47784. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47785. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47786. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47787. }
  47788. }
  47789. };
  47790. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47791. return "FreeCameraKeyboardMoveInput";
  47792. };
  47793. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47794. this._keys = [];
  47795. };
  47796. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47797. return "keyboard";
  47798. };
  47799. __decorate([
  47800. BABYLON.serialize()
  47801. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47802. __decorate([
  47803. BABYLON.serialize()
  47804. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47805. __decorate([
  47806. BABYLON.serialize()
  47807. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47808. __decorate([
  47809. BABYLON.serialize()
  47810. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47811. return FreeCameraKeyboardMoveInput;
  47812. }());
  47813. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47814. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47815. })(BABYLON || (BABYLON = {}));
  47816. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47817. var BABYLON;
  47818. (function (BABYLON) {
  47819. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47820. __extends(FreeCameraInputsManager, _super);
  47821. function FreeCameraInputsManager(camera) {
  47822. return _super.call(this, camera) || this;
  47823. }
  47824. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47825. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47826. return this;
  47827. };
  47828. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47829. if (touchEnabled === void 0) { touchEnabled = true; }
  47830. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47831. return this;
  47832. };
  47833. FreeCameraInputsManager.prototype.addGamepad = function () {
  47834. this.add(new BABYLON.FreeCameraGamepadInput());
  47835. return this;
  47836. };
  47837. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47838. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47839. return this;
  47840. };
  47841. FreeCameraInputsManager.prototype.addTouch = function () {
  47842. this.add(new BABYLON.FreeCameraTouchInput());
  47843. return this;
  47844. };
  47845. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47846. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47847. return this;
  47848. };
  47849. return FreeCameraInputsManager;
  47850. }(BABYLON.CameraInputsManager));
  47851. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47852. })(BABYLON || (BABYLON = {}));
  47853. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47854. var BABYLON;
  47855. (function (BABYLON) {
  47856. var FreeCamera = /** @class */ (function (_super) {
  47857. __extends(FreeCamera, _super);
  47858. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47859. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47860. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47861. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47862. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47863. _this.checkCollisions = false;
  47864. _this.applyGravity = false;
  47865. _this._needMoveForGravity = false;
  47866. _this._oldPosition = BABYLON.Vector3.Zero();
  47867. _this._diffPosition = BABYLON.Vector3.Zero();
  47868. _this._newPosition = BABYLON.Vector3.Zero();
  47869. // Collisions
  47870. _this._collisionMask = -1;
  47871. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47872. if (collidedMesh === void 0) { collidedMesh = null; }
  47873. //TODO move this to the collision coordinator!
  47874. if (_this.getScene().workerCollisions)
  47875. newPosition.multiplyInPlace(_this._collider._radius);
  47876. var updatePosition = function (newPos) {
  47877. _this._newPosition.copyFrom(newPos);
  47878. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47879. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47880. _this.position.addInPlace(_this._diffPosition);
  47881. if (_this.onCollide && collidedMesh) {
  47882. _this.onCollide(collidedMesh);
  47883. }
  47884. }
  47885. };
  47886. updatePosition(newPosition);
  47887. };
  47888. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47889. _this.inputs.addKeyboard().addMouse();
  47890. return _this;
  47891. }
  47892. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47893. //-- begin properties for backward compatibility for inputs
  47894. /**
  47895. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47896. * Higher values reduce sensitivity.
  47897. */
  47898. get: function () {
  47899. var mouse = this.inputs.attached["mouse"];
  47900. if (mouse)
  47901. return mouse.angularSensibility;
  47902. return 0;
  47903. },
  47904. /**
  47905. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47906. * Higher values reduce sensitivity.
  47907. */
  47908. set: function (value) {
  47909. var mouse = this.inputs.attached["mouse"];
  47910. if (mouse)
  47911. mouse.angularSensibility = value;
  47912. },
  47913. enumerable: true,
  47914. configurable: true
  47915. });
  47916. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47917. get: function () {
  47918. var keyboard = this.inputs.attached["keyboard"];
  47919. if (keyboard)
  47920. return keyboard.keysUp;
  47921. return [];
  47922. },
  47923. set: function (value) {
  47924. var keyboard = this.inputs.attached["keyboard"];
  47925. if (keyboard)
  47926. keyboard.keysUp = value;
  47927. },
  47928. enumerable: true,
  47929. configurable: true
  47930. });
  47931. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47932. get: function () {
  47933. var keyboard = this.inputs.attached["keyboard"];
  47934. if (keyboard)
  47935. return keyboard.keysDown;
  47936. return [];
  47937. },
  47938. set: function (value) {
  47939. var keyboard = this.inputs.attached["keyboard"];
  47940. if (keyboard)
  47941. keyboard.keysDown = value;
  47942. },
  47943. enumerable: true,
  47944. configurable: true
  47945. });
  47946. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47947. get: function () {
  47948. var keyboard = this.inputs.attached["keyboard"];
  47949. if (keyboard)
  47950. return keyboard.keysLeft;
  47951. return [];
  47952. },
  47953. set: function (value) {
  47954. var keyboard = this.inputs.attached["keyboard"];
  47955. if (keyboard)
  47956. keyboard.keysLeft = value;
  47957. },
  47958. enumerable: true,
  47959. configurable: true
  47960. });
  47961. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47962. get: function () {
  47963. var keyboard = this.inputs.attached["keyboard"];
  47964. if (keyboard)
  47965. return keyboard.keysRight;
  47966. return [];
  47967. },
  47968. set: function (value) {
  47969. var keyboard = this.inputs.attached["keyboard"];
  47970. if (keyboard)
  47971. keyboard.keysRight = value;
  47972. },
  47973. enumerable: true,
  47974. configurable: true
  47975. });
  47976. // Controls
  47977. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47978. this.inputs.attachElement(element, noPreventDefault);
  47979. };
  47980. FreeCamera.prototype.detachControl = function (element) {
  47981. this.inputs.detachElement(element);
  47982. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47983. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47984. };
  47985. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47986. get: function () {
  47987. return this._collisionMask;
  47988. },
  47989. set: function (mask) {
  47990. this._collisionMask = !isNaN(mask) ? mask : -1;
  47991. },
  47992. enumerable: true,
  47993. configurable: true
  47994. });
  47995. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47996. var globalPosition;
  47997. if (this.parent) {
  47998. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47999. }
  48000. else {
  48001. globalPosition = this.position;
  48002. }
  48003. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48004. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48005. if (!this._collider) {
  48006. this._collider = new BABYLON.Collider();
  48007. }
  48008. this._collider._radius = this.ellipsoid;
  48009. this._collider.collisionMask = this._collisionMask;
  48010. //no need for clone, as long as gravity is not on.
  48011. var actualDisplacement = displacement;
  48012. //add gravity to the direction to prevent the dual-collision checking
  48013. if (this.applyGravity) {
  48014. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48015. actualDisplacement = displacement.add(this.getScene().gravity);
  48016. }
  48017. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48018. };
  48019. FreeCamera.prototype._checkInputs = function () {
  48020. if (!this._localDirection) {
  48021. this._localDirection = BABYLON.Vector3.Zero();
  48022. this._transformedDirection = BABYLON.Vector3.Zero();
  48023. }
  48024. this.inputs.checkInputs();
  48025. _super.prototype._checkInputs.call(this);
  48026. };
  48027. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48028. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48029. };
  48030. FreeCamera.prototype._updatePosition = function () {
  48031. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48032. this._collideWithWorld(this.cameraDirection);
  48033. }
  48034. else {
  48035. _super.prototype._updatePosition.call(this);
  48036. }
  48037. };
  48038. FreeCamera.prototype.dispose = function () {
  48039. this.inputs.clear();
  48040. _super.prototype.dispose.call(this);
  48041. };
  48042. FreeCamera.prototype.getClassName = function () {
  48043. return "FreeCamera";
  48044. };
  48045. __decorate([
  48046. BABYLON.serializeAsVector3()
  48047. ], FreeCamera.prototype, "ellipsoid", void 0);
  48048. __decorate([
  48049. BABYLON.serializeAsVector3()
  48050. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48051. __decorate([
  48052. BABYLON.serialize()
  48053. ], FreeCamera.prototype, "checkCollisions", void 0);
  48054. __decorate([
  48055. BABYLON.serialize()
  48056. ], FreeCamera.prototype, "applyGravity", void 0);
  48057. return FreeCamera;
  48058. }(BABYLON.TargetCamera));
  48059. BABYLON.FreeCamera = FreeCamera;
  48060. })(BABYLON || (BABYLON = {}));
  48061. //# sourceMappingURL=babylon.freeCamera.js.map
  48062. var BABYLON;
  48063. (function (BABYLON) {
  48064. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48065. function ArcRotateCameraKeyboardMoveInput() {
  48066. this._keys = new Array();
  48067. this.keysUp = [38];
  48068. this.keysDown = [40];
  48069. this.keysLeft = [37];
  48070. this.keysRight = [39];
  48071. this.keysReset = [220];
  48072. this.panningSensibility = 50.0;
  48073. this.zoomingSensibility = 25.0;
  48074. this.useAltToZoom = true;
  48075. }
  48076. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48077. var _this = this;
  48078. if (this._onCanvasBlurObserver) {
  48079. return;
  48080. }
  48081. this._scene = this.camera.getScene();
  48082. this._engine = this._scene.getEngine();
  48083. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48084. _this._keys = [];
  48085. });
  48086. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48087. var evt = info.event;
  48088. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48089. _this._ctrlPressed = evt.ctrlKey;
  48090. _this._altPressed = evt.altKey;
  48091. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48092. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48093. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48094. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48095. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48096. var index = _this._keys.indexOf(evt.keyCode);
  48097. if (index === -1) {
  48098. _this._keys.push(evt.keyCode);
  48099. }
  48100. if (evt.preventDefault) {
  48101. if (!noPreventDefault) {
  48102. evt.preventDefault();
  48103. }
  48104. }
  48105. }
  48106. }
  48107. else {
  48108. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48109. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48110. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48111. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48112. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48113. var index = _this._keys.indexOf(evt.keyCode);
  48114. if (index >= 0) {
  48115. _this._keys.splice(index, 1);
  48116. }
  48117. if (evt.preventDefault) {
  48118. if (!noPreventDefault) {
  48119. evt.preventDefault();
  48120. }
  48121. }
  48122. }
  48123. }
  48124. });
  48125. };
  48126. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48127. if (this._scene) {
  48128. if (this._onKeyboardObserver) {
  48129. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48130. }
  48131. if (this._onCanvasBlurObserver) {
  48132. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48133. }
  48134. this._onKeyboardObserver = null;
  48135. this._onCanvasBlurObserver = null;
  48136. }
  48137. this._keys = [];
  48138. };
  48139. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48140. if (this._onKeyboardObserver) {
  48141. var camera = this.camera;
  48142. for (var index = 0; index < this._keys.length; index++) {
  48143. var keyCode = this._keys[index];
  48144. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48145. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48146. camera.inertialPanningX -= 1 / this.panningSensibility;
  48147. }
  48148. else {
  48149. camera.inertialAlphaOffset -= 0.01;
  48150. }
  48151. }
  48152. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48153. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48154. camera.inertialPanningY += 1 / this.panningSensibility;
  48155. }
  48156. else if (this._altPressed && this.useAltToZoom) {
  48157. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48158. }
  48159. else {
  48160. camera.inertialBetaOffset -= 0.01;
  48161. }
  48162. }
  48163. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48164. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48165. camera.inertialPanningX += 1 / this.panningSensibility;
  48166. }
  48167. else {
  48168. camera.inertialAlphaOffset += 0.01;
  48169. }
  48170. }
  48171. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48172. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48173. camera.inertialPanningY -= 1 / this.panningSensibility;
  48174. }
  48175. else if (this._altPressed && this.useAltToZoom) {
  48176. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48177. }
  48178. else {
  48179. camera.inertialBetaOffset += 0.01;
  48180. }
  48181. }
  48182. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48183. camera.restoreState();
  48184. }
  48185. }
  48186. }
  48187. };
  48188. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48189. return "ArcRotateCameraKeyboardMoveInput";
  48190. };
  48191. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48192. return "keyboard";
  48193. };
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48197. __decorate([
  48198. BABYLON.serialize()
  48199. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48200. __decorate([
  48201. BABYLON.serialize()
  48202. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48209. __decorate([
  48210. BABYLON.serialize()
  48211. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48212. __decorate([
  48213. BABYLON.serialize()
  48214. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48215. __decorate([
  48216. BABYLON.serialize()
  48217. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48218. return ArcRotateCameraKeyboardMoveInput;
  48219. }());
  48220. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48221. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48222. })(BABYLON || (BABYLON = {}));
  48223. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48224. var BABYLON;
  48225. (function (BABYLON) {
  48226. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48227. function ArcRotateCameraMouseWheelInput() {
  48228. this.wheelPrecision = 3.0;
  48229. /**
  48230. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48231. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48232. */
  48233. this.wheelDeltaPercentage = 0;
  48234. }
  48235. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48236. var _this = this;
  48237. this._wheel = function (p, s) {
  48238. //sanity check - this should be a PointerWheel event.
  48239. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48240. return;
  48241. var event = p.event;
  48242. var delta = 0;
  48243. if (event.wheelDelta) {
  48244. if (_this.wheelDeltaPercentage) {
  48245. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48246. if (event.wheelDelta > 0) {
  48247. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48248. }
  48249. else {
  48250. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48251. }
  48252. }
  48253. else {
  48254. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48255. }
  48256. }
  48257. else if (event.detail) {
  48258. delta = -event.detail / _this.wheelPrecision;
  48259. }
  48260. if (delta)
  48261. _this.camera.inertialRadiusOffset += delta;
  48262. if (event.preventDefault) {
  48263. if (!noPreventDefault) {
  48264. event.preventDefault();
  48265. }
  48266. }
  48267. };
  48268. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48269. };
  48270. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48271. if (this._observer && element) {
  48272. this.camera.getScene().onPointerObservable.remove(this._observer);
  48273. this._observer = null;
  48274. this._wheel = null;
  48275. }
  48276. };
  48277. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48278. return "ArcRotateCameraMouseWheelInput";
  48279. };
  48280. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48281. return "mousewheel";
  48282. };
  48283. __decorate([
  48284. BABYLON.serialize()
  48285. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48286. __decorate([
  48287. BABYLON.serialize()
  48288. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48289. return ArcRotateCameraMouseWheelInput;
  48290. }());
  48291. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48292. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48293. })(BABYLON || (BABYLON = {}));
  48294. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48295. var BABYLON;
  48296. (function (BABYLON) {
  48297. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48298. function ArcRotateCameraPointersInput() {
  48299. this.buttons = [0, 1, 2];
  48300. this.angularSensibilityX = 1000.0;
  48301. this.angularSensibilityY = 1000.0;
  48302. this.pinchPrecision = 12.0;
  48303. /**
  48304. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48305. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48306. */
  48307. this.pinchDeltaPercentage = 0;
  48308. this.panningSensibility = 1000.0;
  48309. this.multiTouchPanning = true;
  48310. this.multiTouchPanAndZoom = true;
  48311. this._isPanClick = false;
  48312. this.pinchInwards = true;
  48313. }
  48314. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48315. var _this = this;
  48316. var engine = this.camera.getEngine();
  48317. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48318. var pointA = null;
  48319. var pointB = null;
  48320. var previousPinchSquaredDistance = 0;
  48321. var initialDistance = 0;
  48322. var twoFingerActivityCount = 0;
  48323. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48324. this._pointerInput = function (p, s) {
  48325. var evt = p.event;
  48326. var isTouch = p.event.pointerType === "touch";
  48327. if (engine.isInVRExclusivePointerMode) {
  48328. return;
  48329. }
  48330. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48331. return;
  48332. }
  48333. var srcElement = (evt.srcElement || evt.target);
  48334. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48335. try {
  48336. srcElement.setPointerCapture(evt.pointerId);
  48337. }
  48338. catch (e) {
  48339. //Nothing to do with the error. Execution will continue.
  48340. }
  48341. // Manage panning with pan button click
  48342. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48343. // manage pointers
  48344. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48345. if (pointA === null) {
  48346. pointA = cacheSoloPointer;
  48347. }
  48348. else if (pointB === null) {
  48349. pointB = cacheSoloPointer;
  48350. }
  48351. if (!noPreventDefault) {
  48352. evt.preventDefault();
  48353. element.focus();
  48354. }
  48355. }
  48356. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48357. _this.camera.restoreState();
  48358. }
  48359. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48360. try {
  48361. srcElement.releasePointerCapture(evt.pointerId);
  48362. }
  48363. catch (e) {
  48364. //Nothing to do with the error.
  48365. }
  48366. cacheSoloPointer = null;
  48367. previousPinchSquaredDistance = 0;
  48368. previousMultiTouchPanPosition.isPaning = false;
  48369. previousMultiTouchPanPosition.isPinching = false;
  48370. twoFingerActivityCount = 0;
  48371. initialDistance = 0;
  48372. if (!isTouch) {
  48373. pointB = null; // Mouse and pen are mono pointer
  48374. }
  48375. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48376. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48377. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48378. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48379. if (engine._badOS) {
  48380. pointA = pointB = null;
  48381. }
  48382. else {
  48383. //only remove the impacted pointer in case of multitouch allowing on most
  48384. //platforms switching from rotate to zoom and pan seamlessly.
  48385. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48386. pointA = pointB;
  48387. pointB = null;
  48388. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48389. }
  48390. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48391. pointB = null;
  48392. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48393. }
  48394. else {
  48395. pointA = pointB = null;
  48396. }
  48397. }
  48398. if (!noPreventDefault) {
  48399. evt.preventDefault();
  48400. }
  48401. }
  48402. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48403. if (!noPreventDefault) {
  48404. evt.preventDefault();
  48405. }
  48406. // One button down
  48407. if (pointA && pointB === null && cacheSoloPointer) {
  48408. if (_this.panningSensibility !== 0 &&
  48409. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48410. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48411. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48412. }
  48413. else {
  48414. var offsetX = evt.clientX - cacheSoloPointer.x;
  48415. var offsetY = evt.clientY - cacheSoloPointer.y;
  48416. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48417. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48418. }
  48419. cacheSoloPointer.x = evt.clientX;
  48420. cacheSoloPointer.y = evt.clientY;
  48421. }
  48422. // Two buttons down: pinch/pan
  48423. else if (pointA && pointB) {
  48424. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48425. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48426. ed.x = evt.clientX;
  48427. ed.y = evt.clientY;
  48428. var direction = _this.pinchInwards ? 1 : -1;
  48429. var distX = pointA.x - pointB.x;
  48430. var distY = pointA.y - pointB.y;
  48431. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48432. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48433. if (previousPinchSquaredDistance === 0) {
  48434. initialDistance = pinchDistance;
  48435. previousPinchSquaredDistance = pinchSquaredDistance;
  48436. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48437. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48438. return;
  48439. }
  48440. if (_this.multiTouchPanAndZoom) {
  48441. if (_this.pinchDeltaPercentage) {
  48442. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48443. }
  48444. else {
  48445. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48446. (_this.pinchPrecision *
  48447. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48448. direction);
  48449. }
  48450. if (_this.panningSensibility !== 0) {
  48451. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48452. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48453. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48454. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48455. previousMultiTouchPanPosition.x = pointersCenterX;
  48456. previousMultiTouchPanPosition.y = pointersCenterY;
  48457. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48458. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48459. }
  48460. }
  48461. else {
  48462. twoFingerActivityCount++;
  48463. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48464. if (_this.pinchDeltaPercentage) {
  48465. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48466. }
  48467. else {
  48468. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48469. (_this.pinchPrecision *
  48470. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48471. direction);
  48472. }
  48473. previousMultiTouchPanPosition.isPaning = false;
  48474. previousMultiTouchPanPosition.isPinching = true;
  48475. }
  48476. else {
  48477. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48478. if (!previousMultiTouchPanPosition.isPaning) {
  48479. previousMultiTouchPanPosition.isPaning = true;
  48480. previousMultiTouchPanPosition.isPinching = false;
  48481. previousMultiTouchPanPosition.x = ed.x;
  48482. previousMultiTouchPanPosition.y = ed.y;
  48483. return;
  48484. }
  48485. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48486. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48487. }
  48488. }
  48489. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48490. previousMultiTouchPanPosition.x = ed.x;
  48491. previousMultiTouchPanPosition.y = ed.y;
  48492. }
  48493. }
  48494. previousPinchSquaredDistance = pinchSquaredDistance;
  48495. }
  48496. }
  48497. };
  48498. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48499. this._onContextMenu = function (evt) {
  48500. evt.preventDefault();
  48501. };
  48502. if (!this.camera._useCtrlForPanning) {
  48503. element.addEventListener("contextmenu", this._onContextMenu, false);
  48504. }
  48505. this._onLostFocus = function () {
  48506. //this._keys = [];
  48507. pointA = pointB = null;
  48508. previousPinchSquaredDistance = 0;
  48509. previousMultiTouchPanPosition.isPaning = false;
  48510. previousMultiTouchPanPosition.isPinching = false;
  48511. twoFingerActivityCount = 0;
  48512. cacheSoloPointer = null;
  48513. initialDistance = 0;
  48514. };
  48515. this._onMouseMove = function (evt) {
  48516. if (!engine.isPointerLock) {
  48517. return;
  48518. }
  48519. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48520. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48521. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48522. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48523. if (!noPreventDefault) {
  48524. evt.preventDefault();
  48525. }
  48526. };
  48527. this._onGestureStart = function (e) {
  48528. if (window.MSGesture === undefined) {
  48529. return;
  48530. }
  48531. if (!_this._MSGestureHandler) {
  48532. _this._MSGestureHandler = new MSGesture();
  48533. _this._MSGestureHandler.target = element;
  48534. }
  48535. _this._MSGestureHandler.addPointer(e.pointerId);
  48536. };
  48537. this._onGesture = function (e) {
  48538. _this.camera.radius *= e.scale;
  48539. if (e.preventDefault) {
  48540. if (!noPreventDefault) {
  48541. e.stopPropagation();
  48542. e.preventDefault();
  48543. }
  48544. }
  48545. };
  48546. element.addEventListener("mousemove", this._onMouseMove, false);
  48547. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48548. element.addEventListener("MSGestureChange", this._onGesture, false);
  48549. BABYLON.Tools.RegisterTopRootEvents([
  48550. { name: "blur", handler: this._onLostFocus }
  48551. ]);
  48552. };
  48553. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48554. if (this._onLostFocus) {
  48555. BABYLON.Tools.UnregisterTopRootEvents([
  48556. { name: "blur", handler: this._onLostFocus }
  48557. ]);
  48558. }
  48559. if (element && this._observer) {
  48560. this.camera.getScene().onPointerObservable.remove(this._observer);
  48561. this._observer = null;
  48562. if (this._onContextMenu) {
  48563. element.removeEventListener("contextmenu", this._onContextMenu);
  48564. }
  48565. if (this._onMouseMove) {
  48566. element.removeEventListener("mousemove", this._onMouseMove);
  48567. }
  48568. if (this._onGestureStart) {
  48569. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48570. }
  48571. if (this._onGesture) {
  48572. element.removeEventListener("MSGestureChange", this._onGesture);
  48573. }
  48574. this._isPanClick = false;
  48575. this.pinchInwards = true;
  48576. this._onMouseMove = null;
  48577. this._onGestureStart = null;
  48578. this._onGesture = null;
  48579. this._MSGestureHandler = null;
  48580. this._onLostFocus = null;
  48581. this._onContextMenu = null;
  48582. }
  48583. };
  48584. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48585. return "ArcRotateCameraPointersInput";
  48586. };
  48587. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48588. return "pointers";
  48589. };
  48590. __decorate([
  48591. BABYLON.serialize()
  48592. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48593. __decorate([
  48594. BABYLON.serialize()
  48595. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48596. __decorate([
  48597. BABYLON.serialize()
  48598. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48599. __decorate([
  48600. BABYLON.serialize()
  48601. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48602. __decorate([
  48603. BABYLON.serialize()
  48604. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48605. __decorate([
  48606. BABYLON.serialize()
  48607. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48608. __decorate([
  48609. BABYLON.serialize()
  48610. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48611. __decorate([
  48612. BABYLON.serialize()
  48613. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48614. return ArcRotateCameraPointersInput;
  48615. }());
  48616. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48617. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48618. })(BABYLON || (BABYLON = {}));
  48619. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48620. var BABYLON;
  48621. (function (BABYLON) {
  48622. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48623. __extends(ArcRotateCameraInputsManager, _super);
  48624. function ArcRotateCameraInputsManager(camera) {
  48625. return _super.call(this, camera) || this;
  48626. }
  48627. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48628. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48629. return this;
  48630. };
  48631. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48632. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48633. return this;
  48634. };
  48635. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48636. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48637. return this;
  48638. };
  48639. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48640. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48641. return this;
  48642. };
  48643. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48644. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48645. return this;
  48646. };
  48647. return ArcRotateCameraInputsManager;
  48648. }(BABYLON.CameraInputsManager));
  48649. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48650. })(BABYLON || (BABYLON = {}));
  48651. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48652. var BABYLON;
  48653. (function (BABYLON) {
  48654. var ArcRotateCamera = /** @class */ (function (_super) {
  48655. __extends(ArcRotateCamera, _super);
  48656. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48657. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48658. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48659. _this.inertialAlphaOffset = 0;
  48660. _this.inertialBetaOffset = 0;
  48661. _this.inertialRadiusOffset = 0;
  48662. _this.lowerAlphaLimit = null;
  48663. _this.upperAlphaLimit = null;
  48664. _this.lowerBetaLimit = 0.01;
  48665. _this.upperBetaLimit = Math.PI;
  48666. _this.lowerRadiusLimit = null;
  48667. _this.upperRadiusLimit = null;
  48668. _this.inertialPanningX = 0;
  48669. _this.inertialPanningY = 0;
  48670. _this.pinchToPanMaxDistance = 20;
  48671. _this.panningDistanceLimit = null;
  48672. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48673. _this.panningInertia = 0.9;
  48674. //-- end properties for backward compatibility for inputs
  48675. _this.zoomOnFactor = 1;
  48676. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48677. _this.allowUpsideDown = true;
  48678. _this._viewMatrix = new BABYLON.Matrix();
  48679. // Panning
  48680. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48681. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48682. _this.checkCollisions = false;
  48683. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48684. _this._previousPosition = BABYLON.Vector3.Zero();
  48685. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48686. _this._newPosition = BABYLON.Vector3.Zero();
  48687. _this._computationVector = BABYLON.Vector3.Zero();
  48688. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48689. if (collidedMesh === void 0) { collidedMesh = null; }
  48690. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48691. newPosition.multiplyInPlace(_this._collider._radius);
  48692. }
  48693. if (!collidedMesh) {
  48694. _this._previousPosition.copyFrom(_this.position);
  48695. }
  48696. else {
  48697. _this.setPosition(newPosition);
  48698. if (_this.onCollide) {
  48699. _this.onCollide(collidedMesh);
  48700. }
  48701. }
  48702. // Recompute because of constraints
  48703. var cosa = Math.cos(_this.alpha);
  48704. var sina = Math.sin(_this.alpha);
  48705. var cosb = Math.cos(_this.beta);
  48706. var sinb = Math.sin(_this.beta);
  48707. if (sinb === 0) {
  48708. sinb = 0.0001;
  48709. }
  48710. var target = _this._getTargetPosition();
  48711. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48712. target.addToRef(_this._computationVector, _this._newPosition);
  48713. _this.position.copyFrom(_this._newPosition);
  48714. var up = _this.upVector;
  48715. if (_this.allowUpsideDown && _this.beta < 0) {
  48716. up = up.clone();
  48717. up = up.negate();
  48718. }
  48719. _this._computeViewMatrix(_this.position, target, up);
  48720. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48721. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48722. _this._collisionTriggered = false;
  48723. };
  48724. _this._target = BABYLON.Vector3.Zero();
  48725. if (target) {
  48726. _this.setTarget(target);
  48727. }
  48728. _this.alpha = alpha;
  48729. _this.beta = beta;
  48730. _this.radius = radius;
  48731. _this.getViewMatrix();
  48732. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48733. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48734. return _this;
  48735. }
  48736. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48737. get: function () {
  48738. return this._target;
  48739. },
  48740. set: function (value) {
  48741. this.setTarget(value);
  48742. },
  48743. enumerable: true,
  48744. configurable: true
  48745. });
  48746. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48747. //-- begin properties for backward compatibility for inputs
  48748. get: function () {
  48749. var pointers = this.inputs.attached["pointers"];
  48750. if (pointers)
  48751. return pointers.angularSensibilityX;
  48752. return 0;
  48753. },
  48754. set: function (value) {
  48755. var pointers = this.inputs.attached["pointers"];
  48756. if (pointers) {
  48757. pointers.angularSensibilityX = value;
  48758. }
  48759. },
  48760. enumerable: true,
  48761. configurable: true
  48762. });
  48763. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48764. get: function () {
  48765. var pointers = this.inputs.attached["pointers"];
  48766. if (pointers)
  48767. return pointers.angularSensibilityY;
  48768. return 0;
  48769. },
  48770. set: function (value) {
  48771. var pointers = this.inputs.attached["pointers"];
  48772. if (pointers) {
  48773. pointers.angularSensibilityY = value;
  48774. }
  48775. },
  48776. enumerable: true,
  48777. configurable: true
  48778. });
  48779. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48780. get: function () {
  48781. var pointers = this.inputs.attached["pointers"];
  48782. if (pointers)
  48783. return pointers.pinchPrecision;
  48784. return 0;
  48785. },
  48786. set: function (value) {
  48787. var pointers = this.inputs.attached["pointers"];
  48788. if (pointers) {
  48789. pointers.pinchPrecision = value;
  48790. }
  48791. },
  48792. enumerable: true,
  48793. configurable: true
  48794. });
  48795. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48796. get: function () {
  48797. var pointers = this.inputs.attached["pointers"];
  48798. if (pointers)
  48799. return pointers.pinchDeltaPercentage;
  48800. return 0;
  48801. },
  48802. set: function (value) {
  48803. var pointers = this.inputs.attached["pointers"];
  48804. if (pointers) {
  48805. pointers.pinchDeltaPercentage = value;
  48806. }
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48812. get: function () {
  48813. var pointers = this.inputs.attached["pointers"];
  48814. if (pointers)
  48815. return pointers.panningSensibility;
  48816. return 0;
  48817. },
  48818. set: function (value) {
  48819. var pointers = this.inputs.attached["pointers"];
  48820. if (pointers) {
  48821. pointers.panningSensibility = value;
  48822. }
  48823. },
  48824. enumerable: true,
  48825. configurable: true
  48826. });
  48827. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48828. get: function () {
  48829. var keyboard = this.inputs.attached["keyboard"];
  48830. if (keyboard)
  48831. return keyboard.keysUp;
  48832. return [];
  48833. },
  48834. set: function (value) {
  48835. var keyboard = this.inputs.attached["keyboard"];
  48836. if (keyboard)
  48837. keyboard.keysUp = value;
  48838. },
  48839. enumerable: true,
  48840. configurable: true
  48841. });
  48842. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48843. get: function () {
  48844. var keyboard = this.inputs.attached["keyboard"];
  48845. if (keyboard)
  48846. return keyboard.keysDown;
  48847. return [];
  48848. },
  48849. set: function (value) {
  48850. var keyboard = this.inputs.attached["keyboard"];
  48851. if (keyboard)
  48852. keyboard.keysDown = value;
  48853. },
  48854. enumerable: true,
  48855. configurable: true
  48856. });
  48857. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48858. get: function () {
  48859. var keyboard = this.inputs.attached["keyboard"];
  48860. if (keyboard)
  48861. return keyboard.keysLeft;
  48862. return [];
  48863. },
  48864. set: function (value) {
  48865. var keyboard = this.inputs.attached["keyboard"];
  48866. if (keyboard)
  48867. keyboard.keysLeft = value;
  48868. },
  48869. enumerable: true,
  48870. configurable: true
  48871. });
  48872. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48873. get: function () {
  48874. var keyboard = this.inputs.attached["keyboard"];
  48875. if (keyboard)
  48876. return keyboard.keysRight;
  48877. return [];
  48878. },
  48879. set: function (value) {
  48880. var keyboard = this.inputs.attached["keyboard"];
  48881. if (keyboard)
  48882. keyboard.keysRight = value;
  48883. },
  48884. enumerable: true,
  48885. configurable: true
  48886. });
  48887. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48888. get: function () {
  48889. var mousewheel = this.inputs.attached["mousewheel"];
  48890. if (mousewheel)
  48891. return mousewheel.wheelPrecision;
  48892. return 0;
  48893. },
  48894. set: function (value) {
  48895. var mousewheel = this.inputs.attached["mousewheel"];
  48896. if (mousewheel)
  48897. mousewheel.wheelPrecision = value;
  48898. },
  48899. enumerable: true,
  48900. configurable: true
  48901. });
  48902. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48903. get: function () {
  48904. var mousewheel = this.inputs.attached["mousewheel"];
  48905. if (mousewheel)
  48906. return mousewheel.wheelDeltaPercentage;
  48907. return 0;
  48908. },
  48909. set: function (value) {
  48910. var mousewheel = this.inputs.attached["mousewheel"];
  48911. if (mousewheel)
  48912. mousewheel.wheelDeltaPercentage = value;
  48913. },
  48914. enumerable: true,
  48915. configurable: true
  48916. });
  48917. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48918. get: function () {
  48919. return this._bouncingBehavior;
  48920. },
  48921. enumerable: true,
  48922. configurable: true
  48923. });
  48924. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48925. get: function () {
  48926. return this._bouncingBehavior != null;
  48927. },
  48928. set: function (value) {
  48929. if (value === this.useBouncingBehavior) {
  48930. return;
  48931. }
  48932. if (value) {
  48933. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48934. this.addBehavior(this._bouncingBehavior);
  48935. }
  48936. else if (this._bouncingBehavior) {
  48937. this.removeBehavior(this._bouncingBehavior);
  48938. this._bouncingBehavior = null;
  48939. }
  48940. },
  48941. enumerable: true,
  48942. configurable: true
  48943. });
  48944. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48945. get: function () {
  48946. return this._framingBehavior;
  48947. },
  48948. enumerable: true,
  48949. configurable: true
  48950. });
  48951. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48952. get: function () {
  48953. return this._framingBehavior != null;
  48954. },
  48955. set: function (value) {
  48956. if (value === this.useFramingBehavior) {
  48957. return;
  48958. }
  48959. if (value) {
  48960. this._framingBehavior = new BABYLON.FramingBehavior();
  48961. this.addBehavior(this._framingBehavior);
  48962. }
  48963. else if (this._framingBehavior) {
  48964. this.removeBehavior(this._framingBehavior);
  48965. this._framingBehavior = null;
  48966. }
  48967. },
  48968. enumerable: true,
  48969. configurable: true
  48970. });
  48971. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48972. get: function () {
  48973. return this._autoRotationBehavior;
  48974. },
  48975. enumerable: true,
  48976. configurable: true
  48977. });
  48978. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48979. get: function () {
  48980. return this._autoRotationBehavior != null;
  48981. },
  48982. set: function (value) {
  48983. if (value === this.useAutoRotationBehavior) {
  48984. return;
  48985. }
  48986. if (value) {
  48987. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48988. this.addBehavior(this._autoRotationBehavior);
  48989. }
  48990. else if (this._autoRotationBehavior) {
  48991. this.removeBehavior(this._autoRotationBehavior);
  48992. this._autoRotationBehavior = null;
  48993. }
  48994. },
  48995. enumerable: true,
  48996. configurable: true
  48997. });
  48998. // Cache
  48999. ArcRotateCamera.prototype._initCache = function () {
  49000. _super.prototype._initCache.call(this);
  49001. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49002. this._cache.alpha = undefined;
  49003. this._cache.beta = undefined;
  49004. this._cache.radius = undefined;
  49005. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49006. };
  49007. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49008. if (!ignoreParentClass) {
  49009. _super.prototype._updateCache.call(this);
  49010. }
  49011. this._cache._target.copyFrom(this._getTargetPosition());
  49012. this._cache.alpha = this.alpha;
  49013. this._cache.beta = this.beta;
  49014. this._cache.radius = this.radius;
  49015. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49016. };
  49017. ArcRotateCamera.prototype._getTargetPosition = function () {
  49018. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49019. var pos = this._targetHost.getAbsolutePosition();
  49020. if (this._targetBoundingCenter) {
  49021. pos.addToRef(this._targetBoundingCenter, this._target);
  49022. }
  49023. else {
  49024. this._target.copyFrom(pos);
  49025. }
  49026. }
  49027. var lockedTargetPosition = this._getLockedTargetPosition();
  49028. if (lockedTargetPosition) {
  49029. return lockedTargetPosition;
  49030. }
  49031. return this._target;
  49032. };
  49033. ArcRotateCamera.prototype.storeState = function () {
  49034. this._storedAlpha = this.alpha;
  49035. this._storedBeta = this.beta;
  49036. this._storedRadius = this.radius;
  49037. this._storedTarget = this._getTargetPosition().clone();
  49038. return _super.prototype.storeState.call(this);
  49039. };
  49040. /**
  49041. * Restored camera state. You must call storeState() first
  49042. */
  49043. ArcRotateCamera.prototype._restoreStateValues = function () {
  49044. if (!_super.prototype._restoreStateValues.call(this)) {
  49045. return false;
  49046. }
  49047. this.alpha = this._storedAlpha;
  49048. this.beta = this._storedBeta;
  49049. this.radius = this._storedRadius;
  49050. this.setTarget(this._storedTarget.clone());
  49051. this.inertialAlphaOffset = 0;
  49052. this.inertialBetaOffset = 0;
  49053. this.inertialRadiusOffset = 0;
  49054. this.inertialPanningX = 0;
  49055. this.inertialPanningY = 0;
  49056. return true;
  49057. };
  49058. // Synchronized
  49059. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49060. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49061. return false;
  49062. return this._cache._target.equals(this._getTargetPosition())
  49063. && this._cache.alpha === this.alpha
  49064. && this._cache.beta === this.beta
  49065. && this._cache.radius === this.radius
  49066. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49067. };
  49068. // Methods
  49069. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49070. var _this = this;
  49071. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49072. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49073. this._useCtrlForPanning = useCtrlForPanning;
  49074. this._panningMouseButton = panningMouseButton;
  49075. this.inputs.attachElement(element, noPreventDefault);
  49076. this._reset = function () {
  49077. _this.inertialAlphaOffset = 0;
  49078. _this.inertialBetaOffset = 0;
  49079. _this.inertialRadiusOffset = 0;
  49080. _this.inertialPanningX = 0;
  49081. _this.inertialPanningY = 0;
  49082. };
  49083. };
  49084. ArcRotateCamera.prototype.detachControl = function (element) {
  49085. this.inputs.detachElement(element);
  49086. if (this._reset) {
  49087. this._reset();
  49088. }
  49089. };
  49090. ArcRotateCamera.prototype._checkInputs = function () {
  49091. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49092. if (this._collisionTriggered) {
  49093. return;
  49094. }
  49095. this.inputs.checkInputs();
  49096. // Inertia
  49097. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49098. var inertialAlphaOffset = this.inertialAlphaOffset;
  49099. if (this.beta <= 0)
  49100. inertialAlphaOffset *= -1;
  49101. if (this.getScene().useRightHandedSystem)
  49102. inertialAlphaOffset *= -1;
  49103. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49104. inertialAlphaOffset *= -1;
  49105. this.alpha += inertialAlphaOffset;
  49106. this.beta += this.inertialBetaOffset;
  49107. this.radius -= this.inertialRadiusOffset;
  49108. this.inertialAlphaOffset *= this.inertia;
  49109. this.inertialBetaOffset *= this.inertia;
  49110. this.inertialRadiusOffset *= this.inertia;
  49111. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49112. this.inertialAlphaOffset = 0;
  49113. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49114. this.inertialBetaOffset = 0;
  49115. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49116. this.inertialRadiusOffset = 0;
  49117. }
  49118. // Panning inertia
  49119. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49120. if (!this._localDirection) {
  49121. this._localDirection = BABYLON.Vector3.Zero();
  49122. this._transformedDirection = BABYLON.Vector3.Zero();
  49123. }
  49124. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49125. this._localDirection.multiplyInPlace(this.panningAxis);
  49126. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49127. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49128. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49129. if (!this.panningAxis.y) {
  49130. this._transformedDirection.y = 0;
  49131. }
  49132. if (!this._targetHost) {
  49133. if (this.panningDistanceLimit) {
  49134. this._transformedDirection.addInPlace(this._target);
  49135. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49136. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49137. this._target.copyFrom(this._transformedDirection);
  49138. }
  49139. }
  49140. else {
  49141. this._target.addInPlace(this._transformedDirection);
  49142. }
  49143. }
  49144. this.inertialPanningX *= this.panningInertia;
  49145. this.inertialPanningY *= this.panningInertia;
  49146. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49147. this.inertialPanningX = 0;
  49148. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49149. this.inertialPanningY = 0;
  49150. }
  49151. // Limits
  49152. this._checkLimits();
  49153. _super.prototype._checkInputs.call(this);
  49154. };
  49155. ArcRotateCamera.prototype._checkLimits = function () {
  49156. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49157. if (this.allowUpsideDown && this.beta > Math.PI) {
  49158. this.beta = this.beta - (2 * Math.PI);
  49159. }
  49160. }
  49161. else {
  49162. if (this.beta < this.lowerBetaLimit) {
  49163. this.beta = this.lowerBetaLimit;
  49164. }
  49165. }
  49166. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49167. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49168. this.beta = this.beta + (2 * Math.PI);
  49169. }
  49170. }
  49171. else {
  49172. if (this.beta > this.upperBetaLimit) {
  49173. this.beta = this.upperBetaLimit;
  49174. }
  49175. }
  49176. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49177. this.alpha = this.lowerAlphaLimit;
  49178. }
  49179. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49180. this.alpha = this.upperAlphaLimit;
  49181. }
  49182. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49183. this.radius = this.lowerRadiusLimit;
  49184. }
  49185. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49186. this.radius = this.upperRadiusLimit;
  49187. }
  49188. };
  49189. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49190. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49191. this.radius = this._computationVector.length();
  49192. if (this.radius === 0) {
  49193. this.radius = 0.0001; // Just to avoid division by zero
  49194. }
  49195. // Alpha
  49196. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49197. if (this._computationVector.z < 0) {
  49198. this.alpha = 2 * Math.PI - this.alpha;
  49199. }
  49200. // Beta
  49201. this.beta = Math.acos(this._computationVector.y / this.radius);
  49202. this._checkLimits();
  49203. };
  49204. ArcRotateCamera.prototype.setPosition = function (position) {
  49205. if (this.position.equals(position)) {
  49206. return;
  49207. }
  49208. this.position.copyFrom(position);
  49209. this.rebuildAnglesAndRadius();
  49210. };
  49211. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49212. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49213. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49214. if (target.getBoundingInfo) {
  49215. if (toBoundingCenter) {
  49216. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49217. }
  49218. else {
  49219. this._targetBoundingCenter = null;
  49220. }
  49221. this._targetHost = target;
  49222. this._target = this._getTargetPosition();
  49223. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49224. }
  49225. else {
  49226. var newTarget = target;
  49227. var currentTarget = this._getTargetPosition();
  49228. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49229. return;
  49230. }
  49231. this._targetHost = null;
  49232. this._target = newTarget;
  49233. this._targetBoundingCenter = null;
  49234. this.onMeshTargetChangedObservable.notifyObservers(null);
  49235. }
  49236. this.rebuildAnglesAndRadius();
  49237. };
  49238. ArcRotateCamera.prototype._getViewMatrix = function () {
  49239. // Compute
  49240. var cosa = Math.cos(this.alpha);
  49241. var sina = Math.sin(this.alpha);
  49242. var cosb = Math.cos(this.beta);
  49243. var sinb = Math.sin(this.beta);
  49244. if (sinb === 0) {
  49245. sinb = 0.0001;
  49246. }
  49247. var target = this._getTargetPosition();
  49248. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49249. target.addToRef(this._computationVector, this._newPosition);
  49250. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49251. if (!this._collider) {
  49252. this._collider = new BABYLON.Collider();
  49253. }
  49254. this._collider._radius = this.collisionRadius;
  49255. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49256. this._collisionTriggered = true;
  49257. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49258. }
  49259. else {
  49260. this.position.copyFrom(this._newPosition);
  49261. var up = this.upVector;
  49262. if (this.allowUpsideDown && sinb < 0) {
  49263. up = up.clone();
  49264. up = up.negate();
  49265. }
  49266. this._computeViewMatrix(this.position, target, up);
  49267. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49268. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49269. }
  49270. this._currentTarget = target;
  49271. return this._viewMatrix;
  49272. };
  49273. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49274. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49275. meshes = meshes || this.getScene().meshes;
  49276. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49277. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49278. this.radius = distance * this.zoomOnFactor;
  49279. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49280. };
  49281. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49282. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49283. var meshesOrMinMaxVector;
  49284. var distance;
  49285. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49286. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49287. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49288. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49289. }
  49290. else { //minMaxVector and distance
  49291. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49292. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49293. distance = minMaxVectorAndDistance.distance;
  49294. }
  49295. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49296. if (!doNotUpdateMaxZ) {
  49297. this.maxZ = distance * 2;
  49298. }
  49299. };
  49300. /**
  49301. * @override
  49302. * Override Camera.createRigCamera
  49303. */
  49304. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49305. var alphaShift = 0;
  49306. switch (this.cameraRigMode) {
  49307. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49308. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49309. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49310. case BABYLON.Camera.RIG_MODE_VR:
  49311. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49312. break;
  49313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49314. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49315. break;
  49316. }
  49317. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49318. rigCam._cameraRigParams = {};
  49319. return rigCam;
  49320. };
  49321. /**
  49322. * @override
  49323. * Override Camera._updateRigCameras
  49324. */
  49325. ArcRotateCamera.prototype._updateRigCameras = function () {
  49326. var camLeft = this._rigCameras[0];
  49327. var camRight = this._rigCameras[1];
  49328. camLeft.beta = camRight.beta = this.beta;
  49329. camLeft.radius = camRight.radius = this.radius;
  49330. switch (this.cameraRigMode) {
  49331. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49332. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49333. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49334. case BABYLON.Camera.RIG_MODE_VR:
  49335. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49336. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49337. break;
  49338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49339. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49340. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49341. break;
  49342. }
  49343. _super.prototype._updateRigCameras.call(this);
  49344. };
  49345. ArcRotateCamera.prototype.dispose = function () {
  49346. this.inputs.clear();
  49347. _super.prototype.dispose.call(this);
  49348. };
  49349. ArcRotateCamera.prototype.getClassName = function () {
  49350. return "ArcRotateCamera";
  49351. };
  49352. __decorate([
  49353. BABYLON.serialize()
  49354. ], ArcRotateCamera.prototype, "alpha", void 0);
  49355. __decorate([
  49356. BABYLON.serialize()
  49357. ], ArcRotateCamera.prototype, "beta", void 0);
  49358. __decorate([
  49359. BABYLON.serialize()
  49360. ], ArcRotateCamera.prototype, "radius", void 0);
  49361. __decorate([
  49362. BABYLON.serializeAsVector3("target")
  49363. ], ArcRotateCamera.prototype, "_target", void 0);
  49364. __decorate([
  49365. BABYLON.serialize()
  49366. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49367. __decorate([
  49368. BABYLON.serialize()
  49369. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49370. __decorate([
  49371. BABYLON.serialize()
  49372. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49373. __decorate([
  49374. BABYLON.serialize()
  49375. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49376. __decorate([
  49377. BABYLON.serialize()
  49378. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49379. __decorate([
  49380. BABYLON.serialize()
  49381. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49382. __decorate([
  49383. BABYLON.serialize()
  49384. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49385. __decorate([
  49386. BABYLON.serialize()
  49387. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49388. __decorate([
  49389. BABYLON.serialize()
  49390. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49391. __decorate([
  49392. BABYLON.serialize()
  49393. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49394. __decorate([
  49395. BABYLON.serialize()
  49396. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49397. __decorate([
  49398. BABYLON.serialize()
  49399. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49400. __decorate([
  49401. BABYLON.serialize()
  49402. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49403. __decorate([
  49404. BABYLON.serializeAsVector3()
  49405. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49406. __decorate([
  49407. BABYLON.serialize()
  49408. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49409. __decorate([
  49410. BABYLON.serialize()
  49411. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49412. __decorate([
  49413. BABYLON.serialize()
  49414. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49415. return ArcRotateCamera;
  49416. }(BABYLON.TargetCamera));
  49417. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49418. })(BABYLON || (BABYLON = {}));
  49419. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49420. var BABYLON;
  49421. (function (BABYLON) {
  49422. /**
  49423. * The HemisphericLight simulates the ambient environment light,
  49424. * so the passed direction is the light reflection direction, not the incoming direction.
  49425. */
  49426. var HemisphericLight = /** @class */ (function (_super) {
  49427. __extends(HemisphericLight, _super);
  49428. /**
  49429. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49430. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49431. * The HemisphericLight can't cast shadows.
  49432. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49433. * @param name The friendly name of the light
  49434. * @param direction The direction of the light reflection
  49435. * @param scene The scene the light belongs to
  49436. */
  49437. function HemisphericLight(name, direction, scene) {
  49438. var _this = _super.call(this, name, scene) || this;
  49439. /**
  49440. * The groundColor is the light in the opposite direction to the one specified during creation.
  49441. * 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.
  49442. */
  49443. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49444. _this.direction = direction || BABYLON.Vector3.Up();
  49445. return _this;
  49446. }
  49447. HemisphericLight.prototype._buildUniformLayout = function () {
  49448. this._uniformBuffer.addUniform("vLightData", 4);
  49449. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49450. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49451. this._uniformBuffer.addUniform("vLightGround", 3);
  49452. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49453. this._uniformBuffer.addUniform("depthValues", 2);
  49454. this._uniformBuffer.create();
  49455. };
  49456. /**
  49457. * Returns the string "HemisphericLight".
  49458. * @return The class name
  49459. */
  49460. HemisphericLight.prototype.getClassName = function () {
  49461. return "HemisphericLight";
  49462. };
  49463. /**
  49464. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49465. * Returns the updated direction.
  49466. * @param target The target the direction should point to
  49467. * @return The computed direction
  49468. */
  49469. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49470. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49471. return this.direction;
  49472. };
  49473. /**
  49474. * Returns the shadow generator associated to the light.
  49475. * @returns Always null for hemispheric lights because it does not support shadows.
  49476. */
  49477. HemisphericLight.prototype.getShadowGenerator = function () {
  49478. return null;
  49479. };
  49480. /**
  49481. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49482. * @param effect The effect to update
  49483. * @param lightIndex The index of the light in the effect to update
  49484. * @returns The hemispheric light
  49485. */
  49486. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49487. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49488. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49489. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49490. return this;
  49491. };
  49492. /**
  49493. * @hidden internal use only.
  49494. */
  49495. HemisphericLight.prototype._getWorldMatrix = function () {
  49496. if (!this._worldMatrix) {
  49497. this._worldMatrix = BABYLON.Matrix.Identity();
  49498. }
  49499. return this._worldMatrix;
  49500. };
  49501. /**
  49502. * Returns the integer 3.
  49503. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49504. */
  49505. HemisphericLight.prototype.getTypeID = function () {
  49506. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49507. };
  49508. __decorate([
  49509. BABYLON.serializeAsColor3()
  49510. ], HemisphericLight.prototype, "groundColor", void 0);
  49511. __decorate([
  49512. BABYLON.serializeAsVector3()
  49513. ], HemisphericLight.prototype, "direction", void 0);
  49514. return HemisphericLight;
  49515. }(BABYLON.Light));
  49516. BABYLON.HemisphericLight = HemisphericLight;
  49517. })(BABYLON || (BABYLON = {}));
  49518. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49519. var BABYLON;
  49520. (function (BABYLON) {
  49521. /**
  49522. * Base implementation IShadowLight
  49523. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49524. */
  49525. var ShadowLight = /** @class */ (function (_super) {
  49526. __extends(ShadowLight, _super);
  49527. function ShadowLight() {
  49528. var _this = _super !== null && _super.apply(this, arguments) || this;
  49529. _this._needProjectionMatrixCompute = true;
  49530. return _this;
  49531. }
  49532. ShadowLight.prototype._setPosition = function (value) {
  49533. this._position = value;
  49534. };
  49535. Object.defineProperty(ShadowLight.prototype, "position", {
  49536. /**
  49537. * Sets the position the shadow will be casted from. Also use as the light position for both
  49538. * point and spot lights.
  49539. */
  49540. get: function () {
  49541. return this._position;
  49542. },
  49543. /**
  49544. * Sets the position the shadow will be casted from. Also use as the light position for both
  49545. * point and spot lights.
  49546. */
  49547. set: function (value) {
  49548. this._setPosition(value);
  49549. },
  49550. enumerable: true,
  49551. configurable: true
  49552. });
  49553. ShadowLight.prototype._setDirection = function (value) {
  49554. this._direction = value;
  49555. };
  49556. Object.defineProperty(ShadowLight.prototype, "direction", {
  49557. /**
  49558. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49559. * Also use as the light direction on spot and directional lights.
  49560. */
  49561. get: function () {
  49562. return this._direction;
  49563. },
  49564. /**
  49565. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49566. * Also use as the light direction on spot and directional lights.
  49567. */
  49568. set: function (value) {
  49569. this._setDirection(value);
  49570. },
  49571. enumerable: true,
  49572. configurable: true
  49573. });
  49574. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49575. /**
  49576. * Gets the shadow projection clipping minimum z value.
  49577. */
  49578. get: function () {
  49579. return this._shadowMinZ;
  49580. },
  49581. /**
  49582. * Sets the shadow projection clipping minimum z value.
  49583. */
  49584. set: function (value) {
  49585. this._shadowMinZ = value;
  49586. this.forceProjectionMatrixCompute();
  49587. },
  49588. enumerable: true,
  49589. configurable: true
  49590. });
  49591. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49592. /**
  49593. * Sets the shadow projection clipping maximum z value.
  49594. */
  49595. get: function () {
  49596. return this._shadowMaxZ;
  49597. },
  49598. /**
  49599. * Gets the shadow projection clipping maximum z value.
  49600. */
  49601. set: function (value) {
  49602. this._shadowMaxZ = value;
  49603. this.forceProjectionMatrixCompute();
  49604. },
  49605. enumerable: true,
  49606. configurable: true
  49607. });
  49608. /**
  49609. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49610. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49611. */
  49612. ShadowLight.prototype.computeTransformedInformation = function () {
  49613. if (this.parent && this.parent.getWorldMatrix) {
  49614. if (!this.transformedPosition) {
  49615. this.transformedPosition = BABYLON.Vector3.Zero();
  49616. }
  49617. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49618. // In case the direction is present.
  49619. if (this.direction) {
  49620. if (!this.transformedDirection) {
  49621. this.transformedDirection = BABYLON.Vector3.Zero();
  49622. }
  49623. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49624. }
  49625. return true;
  49626. }
  49627. return false;
  49628. };
  49629. /**
  49630. * Return the depth scale used for the shadow map.
  49631. * @returns the depth scale.
  49632. */
  49633. ShadowLight.prototype.getDepthScale = function () {
  49634. return 50.0;
  49635. };
  49636. /**
  49637. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49638. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49639. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49640. */
  49641. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49642. return this.transformedDirection ? this.transformedDirection : this.direction;
  49643. };
  49644. /**
  49645. * Returns the ShadowLight absolute position in the World.
  49646. * @returns the position vector in world space
  49647. */
  49648. ShadowLight.prototype.getAbsolutePosition = function () {
  49649. return this.transformedPosition ? this.transformedPosition : this.position;
  49650. };
  49651. /**
  49652. * Sets the ShadowLight direction toward the passed target.
  49653. * @param target The point tot target in local space
  49654. * @returns the updated ShadowLight direction
  49655. */
  49656. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49657. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49658. return this.direction;
  49659. };
  49660. /**
  49661. * Returns the light rotation in euler definition.
  49662. * @returns the x y z rotation in local space.
  49663. */
  49664. ShadowLight.prototype.getRotation = function () {
  49665. this.direction.normalize();
  49666. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49667. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49668. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49669. };
  49670. /**
  49671. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49672. * @returns true if a cube texture needs to be use
  49673. */
  49674. ShadowLight.prototype.needCube = function () {
  49675. return false;
  49676. };
  49677. /**
  49678. * Detects if the projection matrix requires to be recomputed this frame.
  49679. * @returns true if it requires to be recomputed otherwise, false.
  49680. */
  49681. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49682. return this._needProjectionMatrixCompute;
  49683. };
  49684. /**
  49685. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49686. */
  49687. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49688. this._needProjectionMatrixCompute = true;
  49689. };
  49690. /**
  49691. * Get the world matrix of the sahdow lights.
  49692. * @hidden Internal Use Only
  49693. */
  49694. ShadowLight.prototype._getWorldMatrix = function () {
  49695. if (!this._worldMatrix) {
  49696. this._worldMatrix = BABYLON.Matrix.Identity();
  49697. }
  49698. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49699. return this._worldMatrix;
  49700. };
  49701. /**
  49702. * Gets the minZ used for shadow according to both the scene and the light.
  49703. * @param activeCamera The camera we are returning the min for
  49704. * @returns the depth min z
  49705. */
  49706. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49707. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49708. };
  49709. /**
  49710. * Gets the maxZ used for shadow according to both the scene and the light.
  49711. * @param activeCamera The camera we are returning the max for
  49712. * @returns the depth max z
  49713. */
  49714. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49715. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49716. };
  49717. /**
  49718. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49719. * @param matrix The materix to updated with the projection information
  49720. * @param viewMatrix The transform matrix of the light
  49721. * @param renderList The list of mesh to render in the map
  49722. * @returns The current light
  49723. */
  49724. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49725. if (this.customProjectionMatrixBuilder) {
  49726. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49727. }
  49728. else {
  49729. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49730. }
  49731. return this;
  49732. };
  49733. __decorate([
  49734. BABYLON.serializeAsVector3()
  49735. ], ShadowLight.prototype, "position", null);
  49736. __decorate([
  49737. BABYLON.serializeAsVector3()
  49738. ], ShadowLight.prototype, "direction", null);
  49739. __decorate([
  49740. BABYLON.serialize()
  49741. ], ShadowLight.prototype, "shadowMinZ", null);
  49742. __decorate([
  49743. BABYLON.serialize()
  49744. ], ShadowLight.prototype, "shadowMaxZ", null);
  49745. return ShadowLight;
  49746. }(BABYLON.Light));
  49747. BABYLON.ShadowLight = ShadowLight;
  49748. })(BABYLON || (BABYLON = {}));
  49749. //# sourceMappingURL=babylon.shadowLight.js.map
  49750. var BABYLON;
  49751. (function (BABYLON) {
  49752. /**
  49753. * A point light is a light defined by an unique point in world space.
  49754. * The light is emitted in every direction from this point.
  49755. * A good example of a point light is a standard light bulb.
  49756. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49757. */
  49758. var PointLight = /** @class */ (function (_super) {
  49759. __extends(PointLight, _super);
  49760. /**
  49761. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49762. * A PointLight emits the light in every direction.
  49763. * It can cast shadows.
  49764. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49765. * ```javascript
  49766. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49767. * ```
  49768. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49769. * @param name The light friendly name
  49770. * @param position The position of the point light in the scene
  49771. * @param scene The scene the lights belongs to
  49772. */
  49773. function PointLight(name, position, scene) {
  49774. var _this = _super.call(this, name, scene) || this;
  49775. _this._shadowAngle = Math.PI / 2;
  49776. _this.position = position;
  49777. return _this;
  49778. }
  49779. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49780. /**
  49781. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49782. * This specifies what angle the shadow will use to be created.
  49783. *
  49784. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49785. */
  49786. get: function () {
  49787. return this._shadowAngle;
  49788. },
  49789. /**
  49790. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49791. * This specifies what angle the shadow will use to be created.
  49792. *
  49793. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49794. */
  49795. set: function (value) {
  49796. this._shadowAngle = value;
  49797. this.forceProjectionMatrixCompute();
  49798. },
  49799. enumerable: true,
  49800. configurable: true
  49801. });
  49802. Object.defineProperty(PointLight.prototype, "direction", {
  49803. /**
  49804. * Gets the direction if it has been set.
  49805. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49806. */
  49807. get: function () {
  49808. return this._direction;
  49809. },
  49810. /**
  49811. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49812. */
  49813. set: function (value) {
  49814. var previousNeedCube = this.needCube();
  49815. this._direction = value;
  49816. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49817. this._shadowGenerator.recreateShadowMap();
  49818. }
  49819. },
  49820. enumerable: true,
  49821. configurable: true
  49822. });
  49823. /**
  49824. * Returns the string "PointLight"
  49825. * @returns the class name
  49826. */
  49827. PointLight.prototype.getClassName = function () {
  49828. return "PointLight";
  49829. };
  49830. /**
  49831. * Returns the integer 0.
  49832. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49833. */
  49834. PointLight.prototype.getTypeID = function () {
  49835. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49836. };
  49837. /**
  49838. * Specifies wether or not the shadowmap should be a cube texture.
  49839. * @returns true if the shadowmap needs to be a cube texture.
  49840. */
  49841. PointLight.prototype.needCube = function () {
  49842. return !this.direction;
  49843. };
  49844. /**
  49845. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49846. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49847. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49848. */
  49849. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49850. if (this.direction) {
  49851. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49852. }
  49853. else {
  49854. switch (faceIndex) {
  49855. case 0:
  49856. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49857. case 1:
  49858. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49859. case 2:
  49860. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49861. case 3:
  49862. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49863. case 4:
  49864. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49865. case 5:
  49866. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49867. }
  49868. }
  49869. return BABYLON.Vector3.Zero();
  49870. };
  49871. /**
  49872. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49873. * - fov = PI / 2
  49874. * - aspect ratio : 1.0
  49875. * - z-near and far equal to the active camera minZ and maxZ.
  49876. * Returns the PointLight.
  49877. */
  49878. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49879. var activeCamera = this.getScene().activeCamera;
  49880. if (!activeCamera) {
  49881. return;
  49882. }
  49883. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49884. };
  49885. PointLight.prototype._buildUniformLayout = function () {
  49886. this._uniformBuffer.addUniform("vLightData", 4);
  49887. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49888. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49889. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49890. this._uniformBuffer.addUniform("depthValues", 2);
  49891. this._uniformBuffer.create();
  49892. };
  49893. /**
  49894. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49895. * @param effect The effect to update
  49896. * @param lightIndex The index of the light in the effect to update
  49897. * @returns The point light
  49898. */
  49899. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49900. if (this.computeTransformedInformation()) {
  49901. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49902. return this;
  49903. }
  49904. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49905. return this;
  49906. };
  49907. __decorate([
  49908. BABYLON.serialize()
  49909. ], PointLight.prototype, "shadowAngle", null);
  49910. return PointLight;
  49911. }(BABYLON.ShadowLight));
  49912. BABYLON.PointLight = PointLight;
  49913. })(BABYLON || (BABYLON = {}));
  49914. //# sourceMappingURL=babylon.pointLight.js.map
  49915. var BABYLON;
  49916. (function (BABYLON) {
  49917. /**
  49918. * A directional light is defined by a direction (what a surprise!).
  49919. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49920. * 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.
  49921. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49922. */
  49923. var DirectionalLight = /** @class */ (function (_super) {
  49924. __extends(DirectionalLight, _super);
  49925. /**
  49926. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49927. * The directional light is emitted from everywhere in the given direction.
  49928. * It can cast shawdows.
  49929. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49930. * @param name The friendly name of the light
  49931. * @param direction The direction of the light
  49932. * @param scene The scene the light belongs to
  49933. */
  49934. function DirectionalLight(name, direction, scene) {
  49935. var _this = _super.call(this, name, scene) || this;
  49936. _this._shadowFrustumSize = 0;
  49937. _this._shadowOrthoScale = 0.1;
  49938. /**
  49939. * Automatically compute the projection matrix to best fit (including all the casters)
  49940. * on each frame.
  49941. */
  49942. _this.autoUpdateExtends = true;
  49943. // Cache
  49944. _this._orthoLeft = Number.MAX_VALUE;
  49945. _this._orthoRight = Number.MIN_VALUE;
  49946. _this._orthoTop = Number.MIN_VALUE;
  49947. _this._orthoBottom = Number.MAX_VALUE;
  49948. _this.position = direction.scale(-1.0);
  49949. _this.direction = direction;
  49950. return _this;
  49951. }
  49952. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49953. /**
  49954. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49955. */
  49956. get: function () {
  49957. return this._shadowFrustumSize;
  49958. },
  49959. /**
  49960. * Specifies a fix frustum size for the shadow generation.
  49961. */
  49962. set: function (value) {
  49963. this._shadowFrustumSize = value;
  49964. this.forceProjectionMatrixCompute();
  49965. },
  49966. enumerable: true,
  49967. configurable: true
  49968. });
  49969. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49970. /**
  49971. * Gets the shadow projection scale against the optimal computed one.
  49972. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49973. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49974. */
  49975. get: function () {
  49976. return this._shadowOrthoScale;
  49977. },
  49978. /**
  49979. * Sets the shadow projection scale against the optimal computed one.
  49980. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49981. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49982. */
  49983. set: function (value) {
  49984. this._shadowOrthoScale = value;
  49985. this.forceProjectionMatrixCompute();
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. /**
  49991. * Returns the string "DirectionalLight".
  49992. * @return The class name
  49993. */
  49994. DirectionalLight.prototype.getClassName = function () {
  49995. return "DirectionalLight";
  49996. };
  49997. /**
  49998. * Returns the integer 1.
  49999. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50000. */
  50001. DirectionalLight.prototype.getTypeID = function () {
  50002. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50003. };
  50004. /**
  50005. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50006. * Returns the DirectionalLight Shadow projection matrix.
  50007. */
  50008. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50009. if (this.shadowFrustumSize > 0) {
  50010. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50011. }
  50012. else {
  50013. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50014. }
  50015. };
  50016. /**
  50017. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50018. * Returns the DirectionalLight Shadow projection matrix.
  50019. */
  50020. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50021. var activeCamera = this.getScene().activeCamera;
  50022. if (!activeCamera) {
  50023. return;
  50024. }
  50025. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50026. };
  50027. /**
  50028. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50029. * Returns the DirectionalLight Shadow projection matrix.
  50030. */
  50031. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50032. var activeCamera = this.getScene().activeCamera;
  50033. if (!activeCamera) {
  50034. return;
  50035. }
  50036. // Check extends
  50037. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50038. var tempVector3 = BABYLON.Vector3.Zero();
  50039. this._orthoLeft = Number.MAX_VALUE;
  50040. this._orthoRight = Number.MIN_VALUE;
  50041. this._orthoTop = Number.MIN_VALUE;
  50042. this._orthoBottom = Number.MAX_VALUE;
  50043. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50044. var mesh = renderList[meshIndex];
  50045. if (!mesh) {
  50046. continue;
  50047. }
  50048. var boundingInfo = mesh.getBoundingInfo();
  50049. var boundingBox = boundingInfo.boundingBox;
  50050. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50051. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50052. if (tempVector3.x < this._orthoLeft)
  50053. this._orthoLeft = tempVector3.x;
  50054. if (tempVector3.y < this._orthoBottom)
  50055. this._orthoBottom = tempVector3.y;
  50056. if (tempVector3.x > this._orthoRight)
  50057. this._orthoRight = tempVector3.x;
  50058. if (tempVector3.y > this._orthoTop)
  50059. this._orthoTop = tempVector3.y;
  50060. }
  50061. }
  50062. }
  50063. var xOffset = this._orthoRight - this._orthoLeft;
  50064. var yOffset = this._orthoTop - this._orthoBottom;
  50065. 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);
  50066. };
  50067. DirectionalLight.prototype._buildUniformLayout = function () {
  50068. this._uniformBuffer.addUniform("vLightData", 4);
  50069. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50070. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50071. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50072. this._uniformBuffer.addUniform("depthValues", 2);
  50073. this._uniformBuffer.create();
  50074. };
  50075. /**
  50076. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50077. * @param effect The effect to update
  50078. * @param lightIndex The index of the light in the effect to update
  50079. * @returns The directional light
  50080. */
  50081. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50082. if (this.computeTransformedInformation()) {
  50083. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50084. return this;
  50085. }
  50086. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50087. return this;
  50088. };
  50089. /**
  50090. * Gets the minZ used for shadow according to both the scene and the light.
  50091. *
  50092. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50093. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50094. * @param activeCamera The camera we are returning the min for
  50095. * @returns the depth min z
  50096. */
  50097. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50098. return 1;
  50099. };
  50100. /**
  50101. * Gets the maxZ used for shadow according to both the scene and the light.
  50102. *
  50103. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50104. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50105. * @param activeCamera The camera we are returning the max for
  50106. * @returns the depth max z
  50107. */
  50108. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50109. return 1;
  50110. };
  50111. __decorate([
  50112. BABYLON.serialize()
  50113. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50114. __decorate([
  50115. BABYLON.serialize()
  50116. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50117. __decorate([
  50118. BABYLON.serialize()
  50119. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50120. return DirectionalLight;
  50121. }(BABYLON.ShadowLight));
  50122. BABYLON.DirectionalLight = DirectionalLight;
  50123. })(BABYLON || (BABYLON = {}));
  50124. //# sourceMappingURL=babylon.directionalLight.js.map
  50125. var BABYLON;
  50126. (function (BABYLON) {
  50127. /**
  50128. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50129. * These values define a cone of light starting from the position, emitting toward the direction.
  50130. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50131. * and the exponent defines the speed of the decay of the light with distance (reach).
  50132. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50133. */
  50134. var SpotLight = /** @class */ (function (_super) {
  50135. __extends(SpotLight, _super);
  50136. /**
  50137. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50138. * It can cast shadows.
  50139. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50140. * @param name The light friendly name
  50141. * @param position The position of the spot light in the scene
  50142. * @param direction The direction of the light in the scene
  50143. * @param angle The cone angle of the light in Radians
  50144. * @param exponent The light decay speed with the distance from the emission spot
  50145. * @param scene The scene the lights belongs to
  50146. */
  50147. function SpotLight(name, position, direction, angle, exponent, scene) {
  50148. var _this = _super.call(this, name, scene) || this;
  50149. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50150. _this._projectionTextureLightNear = 1e-6;
  50151. _this._projectionTextureLightFar = 1000.0;
  50152. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50153. _this._projectionTextureViewLightDirty = true;
  50154. _this._projectionTextureProjectionLightDirty = true;
  50155. _this._projectionTextureDirty = true;
  50156. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50157. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50158. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50159. _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);
  50160. _this.position = position;
  50161. _this.direction = direction;
  50162. _this.angle = angle;
  50163. _this.exponent = exponent;
  50164. return _this;
  50165. }
  50166. Object.defineProperty(SpotLight.prototype, "angle", {
  50167. /**
  50168. * Gets the cone angle of the spot light in Radians.
  50169. */
  50170. get: function () {
  50171. return this._angle;
  50172. },
  50173. /**
  50174. * Sets the cone angle of the spot light in Radians.
  50175. */
  50176. set: function (value) {
  50177. this._angle = value;
  50178. this._projectionTextureProjectionLightDirty = true;
  50179. this.forceProjectionMatrixCompute();
  50180. },
  50181. enumerable: true,
  50182. configurable: true
  50183. });
  50184. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50185. /**
  50186. * Allows scaling the angle of the light for shadow generation only.
  50187. */
  50188. get: function () {
  50189. return this._shadowAngleScale;
  50190. },
  50191. /**
  50192. * Allows scaling the angle of the light for shadow generation only.
  50193. */
  50194. set: function (value) {
  50195. this._shadowAngleScale = value;
  50196. this.forceProjectionMatrixCompute();
  50197. },
  50198. enumerable: true,
  50199. configurable: true
  50200. });
  50201. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50202. /**
  50203. * Allows reading the projecton texture
  50204. */
  50205. get: function () {
  50206. return this._projectionTextureMatrix;
  50207. },
  50208. enumerable: true,
  50209. configurable: true
  50210. });
  50211. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50212. /**
  50213. * Gets the near clip of the Spotlight for texture projection.
  50214. */
  50215. get: function () {
  50216. return this._projectionTextureLightNear;
  50217. },
  50218. /**
  50219. * Sets the near clip of the Spotlight for texture projection.
  50220. */
  50221. set: function (value) {
  50222. this._projectionTextureLightNear = value;
  50223. this._projectionTextureProjectionLightDirty = true;
  50224. },
  50225. enumerable: true,
  50226. configurable: true
  50227. });
  50228. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50229. /**
  50230. * Gets the far clip of the Spotlight for texture projection.
  50231. */
  50232. get: function () {
  50233. return this._projectionTextureLightFar;
  50234. },
  50235. /**
  50236. * Sets the far clip of the Spotlight for texture projection.
  50237. */
  50238. set: function (value) {
  50239. this._projectionTextureLightFar = value;
  50240. this._projectionTextureProjectionLightDirty = true;
  50241. },
  50242. enumerable: true,
  50243. configurable: true
  50244. });
  50245. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50246. /**
  50247. * Gets the Up vector of the Spotlight for texture projection.
  50248. */
  50249. get: function () {
  50250. return this._projectionTextureUpDirection;
  50251. },
  50252. /**
  50253. * Sets the Up vector of the Spotlight for texture projection.
  50254. */
  50255. set: function (value) {
  50256. this._projectionTextureUpDirection = value;
  50257. this._projectionTextureProjectionLightDirty = true;
  50258. },
  50259. enumerable: true,
  50260. configurable: true
  50261. });
  50262. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50263. /**
  50264. * Gets the projection texture of the light.
  50265. */
  50266. get: function () {
  50267. return this._projectionTexture;
  50268. },
  50269. /**
  50270. * Sets the projection texture of the light.
  50271. */
  50272. set: function (value) {
  50273. this._projectionTexture = value;
  50274. this._projectionTextureDirty = true;
  50275. },
  50276. enumerable: true,
  50277. configurable: true
  50278. });
  50279. /**
  50280. * Returns the string "SpotLight".
  50281. * @returns the class name
  50282. */
  50283. SpotLight.prototype.getClassName = function () {
  50284. return "SpotLight";
  50285. };
  50286. /**
  50287. * Returns the integer 2.
  50288. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50289. */
  50290. SpotLight.prototype.getTypeID = function () {
  50291. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50292. };
  50293. /**
  50294. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50295. */
  50296. SpotLight.prototype._setDirection = function (value) {
  50297. _super.prototype._setDirection.call(this, value);
  50298. this._projectionTextureViewLightDirty = true;
  50299. };
  50300. /**
  50301. * Overrides the position setter to recompute the projection texture view light Matrix.
  50302. */
  50303. SpotLight.prototype._setPosition = function (value) {
  50304. _super.prototype._setPosition.call(this, value);
  50305. this._projectionTextureViewLightDirty = true;
  50306. };
  50307. /**
  50308. * 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.
  50309. * Returns the SpotLight.
  50310. */
  50311. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50312. var activeCamera = this.getScene().activeCamera;
  50313. if (!activeCamera) {
  50314. return;
  50315. }
  50316. this._shadowAngleScale = this._shadowAngleScale || 1;
  50317. var angle = this._shadowAngleScale * this._angle;
  50318. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50319. };
  50320. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50321. this._projectionTextureViewLightDirty = false;
  50322. this._projectionTextureDirty = true;
  50323. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50324. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50325. };
  50326. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50327. this._projectionTextureProjectionLightDirty = false;
  50328. this._projectionTextureDirty = true;
  50329. var light_far = this.projectionTextureLightFar;
  50330. var light_near = this.projectionTextureLightNear;
  50331. var P = light_far / (light_far - light_near);
  50332. var Q = -P * light_near;
  50333. var S = 1.0 / Math.tan(this._angle / 2.0);
  50334. var A = 1.0;
  50335. 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);
  50336. };
  50337. /**
  50338. * Main function for light texture projection matrix computing.
  50339. */
  50340. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50341. this._projectionTextureDirty = false;
  50342. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50343. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50344. };
  50345. SpotLight.prototype._buildUniformLayout = function () {
  50346. this._uniformBuffer.addUniform("vLightData", 4);
  50347. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50348. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50349. this._uniformBuffer.addUniform("vLightDirection", 3);
  50350. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50351. this._uniformBuffer.addUniform("depthValues", 2);
  50352. this._uniformBuffer.create();
  50353. };
  50354. /**
  50355. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50356. * @param effect The effect to update
  50357. * @param lightIndex The index of the light in the effect to update
  50358. * @returns The spot light
  50359. */
  50360. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50361. var normalizeDirection;
  50362. if (this.computeTransformedInformation()) {
  50363. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50364. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50365. }
  50366. else {
  50367. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50368. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50369. }
  50370. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50371. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50372. if (this._projectionTextureViewLightDirty) {
  50373. this._computeProjectionTextureViewLightMatrix();
  50374. }
  50375. if (this._projectionTextureProjectionLightDirty) {
  50376. this._computeProjectionTextureProjectionLightMatrix();
  50377. }
  50378. if (this._projectionTextureDirty) {
  50379. this._computeProjectionTextureMatrix();
  50380. }
  50381. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50382. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50383. }
  50384. return this;
  50385. };
  50386. /**
  50387. * Disposes the light and the associated resources.
  50388. */
  50389. SpotLight.prototype.dispose = function () {
  50390. _super.prototype.dispose.call(this);
  50391. if (this._projectionTexture) {
  50392. this._projectionTexture.dispose();
  50393. }
  50394. };
  50395. __decorate([
  50396. BABYLON.serialize()
  50397. ], SpotLight.prototype, "angle", null);
  50398. __decorate([
  50399. BABYLON.serialize()
  50400. ], SpotLight.prototype, "shadowAngleScale", null);
  50401. __decorate([
  50402. BABYLON.serialize()
  50403. ], SpotLight.prototype, "exponent", void 0);
  50404. __decorate([
  50405. BABYLON.serialize()
  50406. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50407. __decorate([
  50408. BABYLON.serialize()
  50409. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50410. __decorate([
  50411. BABYLON.serialize()
  50412. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50413. __decorate([
  50414. BABYLON.serializeAsTexture("projectedLightTexture")
  50415. ], SpotLight.prototype, "_projectionTexture", void 0);
  50416. return SpotLight;
  50417. }(BABYLON.ShadowLight));
  50418. BABYLON.SpotLight = SpotLight;
  50419. })(BABYLON || (BABYLON = {}));
  50420. //# sourceMappingURL=babylon.spotLight.js.map
  50421. var BABYLON;
  50422. (function (BABYLON) {
  50423. /**
  50424. * Class used to override all child animations of a given target
  50425. */
  50426. var AnimationPropertiesOverride = /** @class */ (function () {
  50427. function AnimationPropertiesOverride() {
  50428. /**
  50429. * Gets or sets a value indicating if animation blending must be used
  50430. */
  50431. this.enableBlending = false;
  50432. /**
  50433. * Gets or sets the blending speed to use when enableBlending is true
  50434. */
  50435. this.blendingSpeed = 0.01;
  50436. /**
  50437. * Gets or sets the default loop mode to use
  50438. */
  50439. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50440. }
  50441. return AnimationPropertiesOverride;
  50442. }());
  50443. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50444. })(BABYLON || (BABYLON = {}));
  50445. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50446. var BABYLON;
  50447. (function (BABYLON) {
  50448. /**
  50449. * Represents the range of an animation
  50450. */
  50451. var AnimationRange = /** @class */ (function () {
  50452. /**
  50453. * Initializes the range of an animation
  50454. * @param name The name of the animation range
  50455. * @param from The starting frame of the animation
  50456. * @param to The ending frame of the animation
  50457. */
  50458. function AnimationRange(
  50459. /**The name of the animation range**/
  50460. name,
  50461. /**The starting frame of the animation */
  50462. from,
  50463. /**The ending frame of the animation*/
  50464. to) {
  50465. this.name = name;
  50466. this.from = from;
  50467. this.to = to;
  50468. }
  50469. /**
  50470. * Makes a copy of the animation range
  50471. * @returns A copy of the animation range
  50472. */
  50473. AnimationRange.prototype.clone = function () {
  50474. return new AnimationRange(this.name, this.from, this.to);
  50475. };
  50476. return AnimationRange;
  50477. }());
  50478. BABYLON.AnimationRange = AnimationRange;
  50479. /**
  50480. * Composed of a frame, and an action function
  50481. */
  50482. var AnimationEvent = /** @class */ (function () {
  50483. /**
  50484. * Initializes the animation event
  50485. * @param frame The frame for which the event is triggered
  50486. * @param action The event to perform when triggered
  50487. * @param onlyOnce Specifies if the event should be triggered only once
  50488. */
  50489. function AnimationEvent(
  50490. /** The frame for which the event is triggered **/
  50491. frame,
  50492. /** The event to perform when triggered **/
  50493. action,
  50494. /** Specifies if the event should be triggered only once**/
  50495. onlyOnce) {
  50496. this.frame = frame;
  50497. this.action = action;
  50498. this.onlyOnce = onlyOnce;
  50499. /**
  50500. * Specifies if the animation event is done
  50501. */
  50502. this.isDone = false;
  50503. }
  50504. /** @hidden */
  50505. AnimationEvent.prototype._clone = function () {
  50506. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50507. };
  50508. return AnimationEvent;
  50509. }());
  50510. BABYLON.AnimationEvent = AnimationEvent;
  50511. /**
  50512. * A cursor which tracks a point on a path
  50513. */
  50514. var PathCursor = /** @class */ (function () {
  50515. /**
  50516. * Initializes the path cursor
  50517. * @param path The path to track
  50518. */
  50519. function PathCursor(path) {
  50520. this.path = path;
  50521. /**
  50522. * Stores path cursor callbacks for when an onchange event is triggered
  50523. */
  50524. this._onchange = new Array();
  50525. /**
  50526. * The value of the path cursor
  50527. */
  50528. this.value = 0;
  50529. /**
  50530. * The animation array of the path cursor
  50531. */
  50532. this.animations = new Array();
  50533. }
  50534. /**
  50535. * Gets the cursor point on the path
  50536. * @returns A point on the path cursor at the cursor location
  50537. */
  50538. PathCursor.prototype.getPoint = function () {
  50539. var point = this.path.getPointAtLengthPosition(this.value);
  50540. return new BABYLON.Vector3(point.x, 0, point.y);
  50541. };
  50542. /**
  50543. * Moves the cursor ahead by the step amount
  50544. * @param step The amount to move the cursor forward
  50545. * @returns This path cursor
  50546. */
  50547. PathCursor.prototype.moveAhead = function (step) {
  50548. if (step === void 0) { step = 0.002; }
  50549. this.move(step);
  50550. return this;
  50551. };
  50552. /**
  50553. * Moves the cursor behind by the step amount
  50554. * @param step The amount to move the cursor back
  50555. * @returns This path cursor
  50556. */
  50557. PathCursor.prototype.moveBack = function (step) {
  50558. if (step === void 0) { step = 0.002; }
  50559. this.move(-step);
  50560. return this;
  50561. };
  50562. /**
  50563. * Moves the cursor by the step amount
  50564. * If the step amount is greater than one, an exception is thrown
  50565. * @param step The amount to move the cursor
  50566. * @returns This path cursor
  50567. */
  50568. PathCursor.prototype.move = function (step) {
  50569. if (Math.abs(step) > 1) {
  50570. throw "step size should be less than 1.";
  50571. }
  50572. this.value += step;
  50573. this.ensureLimits();
  50574. this.raiseOnChange();
  50575. return this;
  50576. };
  50577. /**
  50578. * Ensures that the value is limited between zero and one
  50579. * @returns This path cursor
  50580. */
  50581. PathCursor.prototype.ensureLimits = function () {
  50582. while (this.value > 1) {
  50583. this.value -= 1;
  50584. }
  50585. while (this.value < 0) {
  50586. this.value += 1;
  50587. }
  50588. return this;
  50589. };
  50590. /**
  50591. * Runs onchange callbacks on change (used by the animation engine)
  50592. * @returns This path cursor
  50593. */
  50594. PathCursor.prototype.raiseOnChange = function () {
  50595. var _this = this;
  50596. this._onchange.forEach(function (f) { return f(_this); });
  50597. return this;
  50598. };
  50599. /**
  50600. * Executes a function on change
  50601. * @param f A path cursor onchange callback
  50602. * @returns This path cursor
  50603. */
  50604. PathCursor.prototype.onchange = function (f) {
  50605. this._onchange.push(f);
  50606. return this;
  50607. };
  50608. return PathCursor;
  50609. }());
  50610. BABYLON.PathCursor = PathCursor;
  50611. /**
  50612. * Enum for the animation key frame interpolation type
  50613. */
  50614. var AnimationKeyInterpolation;
  50615. (function (AnimationKeyInterpolation) {
  50616. /**
  50617. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50618. */
  50619. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50620. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50621. /**
  50622. * Class used to store any kind of animation
  50623. */
  50624. var Animation = /** @class */ (function () {
  50625. /**
  50626. * Initializes the animation
  50627. * @param name Name of the animation
  50628. * @param targetProperty Property to animate
  50629. * @param framePerSecond The frames per second of the animation
  50630. * @param dataType The data type of the animation
  50631. * @param loopMode The loop mode of the animation
  50632. * @param enableBlendings Specifies if blending should be enabled
  50633. */
  50634. function Animation(
  50635. /**Name of the animation */
  50636. name,
  50637. /**Property to animate */
  50638. targetProperty,
  50639. /**The frames per second of the animation */
  50640. framePerSecond,
  50641. /**The data type of the animation */
  50642. dataType,
  50643. /**The loop mode of the animation */
  50644. loopMode,
  50645. /**Specifies if blending should be enabled */
  50646. enableBlending) {
  50647. this.name = name;
  50648. this.targetProperty = targetProperty;
  50649. this.framePerSecond = framePerSecond;
  50650. this.dataType = dataType;
  50651. this.loopMode = loopMode;
  50652. this.enableBlending = enableBlending;
  50653. /**
  50654. * @hidden Internal use only
  50655. */
  50656. this._runtimeAnimations = new Array();
  50657. /**
  50658. * The set of event that will be linked to this animation
  50659. */
  50660. this._events = new Array();
  50661. /**
  50662. * Stores the blending speed of the animation
  50663. */
  50664. this.blendingSpeed = 0.01;
  50665. /**
  50666. * Stores the animation ranges for the animation
  50667. */
  50668. this._ranges = {};
  50669. this.targetPropertyPath = targetProperty.split(".");
  50670. this.dataType = dataType;
  50671. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50672. }
  50673. /**
  50674. * @hidden Internal use
  50675. */
  50676. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50677. var dataType = undefined;
  50678. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50679. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50680. }
  50681. else if (from instanceof BABYLON.Quaternion) {
  50682. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50683. }
  50684. else if (from instanceof BABYLON.Vector3) {
  50685. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50686. }
  50687. else if (from instanceof BABYLON.Vector2) {
  50688. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50689. }
  50690. else if (from instanceof BABYLON.Color3) {
  50691. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50692. }
  50693. else if (from instanceof BABYLON.Size) {
  50694. dataType = Animation.ANIMATIONTYPE_SIZE;
  50695. }
  50696. if (dataType == undefined) {
  50697. return null;
  50698. }
  50699. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50700. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50701. animation.setKeys(keys);
  50702. if (easingFunction !== undefined) {
  50703. animation.setEasingFunction(easingFunction);
  50704. }
  50705. return animation;
  50706. };
  50707. /**
  50708. * Sets up an animation
  50709. * @param property The property to animate
  50710. * @param animationType The animation type to apply
  50711. * @param framePerSecond The frames per second of the animation
  50712. * @param easingFunction The easing function used in the animation
  50713. * @returns The created animation
  50714. */
  50715. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50716. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50717. animation.setEasingFunction(easingFunction);
  50718. return animation;
  50719. };
  50720. /**
  50721. * Create and start an animation on a node
  50722. * @param name defines the name of the global animation that will be run on all nodes
  50723. * @param node defines the root node where the animation will take place
  50724. * @param targetProperty defines property to animate
  50725. * @param framePerSecond defines the number of frame per second yo use
  50726. * @param totalFrame defines the number of frames in total
  50727. * @param from defines the initial value
  50728. * @param to defines the final value
  50729. * @param loopMode defines which loop mode you want to use (off by default)
  50730. * @param easingFunction defines the easing function to use (linear by default)
  50731. * @param onAnimationEnd defines the callback to call when animation end
  50732. * @returns the animatable created for this animation
  50733. */
  50734. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50735. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50736. if (!animation) {
  50737. return null;
  50738. }
  50739. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50740. };
  50741. /**
  50742. * Create and start an animation on a node and its descendants
  50743. * @param name defines the name of the global animation that will be run on all nodes
  50744. * @param node defines the root node where the animation will take place
  50745. * @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
  50746. * @param targetProperty defines property to animate
  50747. * @param framePerSecond defines the number of frame per second to use
  50748. * @param totalFrame defines the number of frames in total
  50749. * @param from defines the initial value
  50750. * @param to defines the final value
  50751. * @param loopMode defines which loop mode you want to use (off by default)
  50752. * @param easingFunction defines the easing function to use (linear by default)
  50753. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50754. * @returns the list of animatables created for all nodes
  50755. * @example https://www.babylonjs-playground.com/#MH0VLI
  50756. */
  50757. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50758. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50759. if (!animation) {
  50760. return null;
  50761. }
  50762. var scene = node.getScene();
  50763. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50764. };
  50765. /**
  50766. * Creates a new animation, merges it with the existing animations and starts it
  50767. * @param name Name of the animation
  50768. * @param node Node which contains the scene that begins the animations
  50769. * @param targetProperty Specifies which property to animate
  50770. * @param framePerSecond The frames per second of the animation
  50771. * @param totalFrame The total number of frames
  50772. * @param from The frame at the beginning of the animation
  50773. * @param to The frame at the end of the animation
  50774. * @param loopMode Specifies the loop mode of the animation
  50775. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50776. * @param onAnimationEnd Callback to run once the animation is complete
  50777. * @returns Nullable animation
  50778. */
  50779. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50780. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50781. if (!animation) {
  50782. return null;
  50783. }
  50784. node.animations.push(animation);
  50785. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50786. };
  50787. /**
  50788. * Transition property of an host to the target Value
  50789. * @param property The property to transition
  50790. * @param targetValue The target Value of the property
  50791. * @param host The object where the property to animate belongs
  50792. * @param scene Scene used to run the animation
  50793. * @param frameRate Framerate (in frame/s) to use
  50794. * @param transition The transition type we want to use
  50795. * @param duration The duration of the animation, in milliseconds
  50796. * @param onAnimationEnd Callback trigger at the end of the animation
  50797. * @returns Nullable animation
  50798. */
  50799. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50800. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50801. if (duration <= 0) {
  50802. host[property] = targetValue;
  50803. if (onAnimationEnd) {
  50804. onAnimationEnd();
  50805. }
  50806. return null;
  50807. }
  50808. var endFrame = frameRate * (duration / 1000);
  50809. transition.setKeys([{
  50810. frame: 0,
  50811. value: host[property].clone ? host[property].clone() : host[property]
  50812. },
  50813. {
  50814. frame: endFrame,
  50815. value: targetValue
  50816. }]);
  50817. if (!host.animations) {
  50818. host.animations = [];
  50819. }
  50820. host.animations.push(transition);
  50821. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50822. animation.onAnimationEnd = onAnimationEnd;
  50823. return animation;
  50824. };
  50825. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50826. /**
  50827. * Return the array of runtime animations currently using this animation
  50828. */
  50829. get: function () {
  50830. return this._runtimeAnimations;
  50831. },
  50832. enumerable: true,
  50833. configurable: true
  50834. });
  50835. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50836. /**
  50837. * Specifies if any of the runtime animations are currently running
  50838. */
  50839. get: function () {
  50840. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50841. var runtimeAnimation = _a[_i];
  50842. if (!runtimeAnimation.isStopped) {
  50843. return true;
  50844. }
  50845. }
  50846. return false;
  50847. },
  50848. enumerable: true,
  50849. configurable: true
  50850. });
  50851. // Methods
  50852. /**
  50853. * Converts the animation to a string
  50854. * @param fullDetails support for multiple levels of logging within scene loading
  50855. * @returns String form of the animation
  50856. */
  50857. Animation.prototype.toString = function (fullDetails) {
  50858. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50859. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50860. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50861. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50862. if (fullDetails) {
  50863. ret += ", Ranges: {";
  50864. var first = true;
  50865. for (var name in this._ranges) {
  50866. if (first) {
  50867. ret += ", ";
  50868. first = false;
  50869. }
  50870. ret += name;
  50871. }
  50872. ret += "}";
  50873. }
  50874. return ret;
  50875. };
  50876. /**
  50877. * Add an event to this animation
  50878. * @param event Event to add
  50879. */
  50880. Animation.prototype.addEvent = function (event) {
  50881. this._events.push(event);
  50882. };
  50883. /**
  50884. * Remove all events found at the given frame
  50885. * @param frame The frame to remove events from
  50886. */
  50887. Animation.prototype.removeEvents = function (frame) {
  50888. for (var index = 0; index < this._events.length; index++) {
  50889. if (this._events[index].frame === frame) {
  50890. this._events.splice(index, 1);
  50891. index--;
  50892. }
  50893. }
  50894. };
  50895. /**
  50896. * Retrieves all the events from the animation
  50897. * @returns Events from the animation
  50898. */
  50899. Animation.prototype.getEvents = function () {
  50900. return this._events;
  50901. };
  50902. /**
  50903. * Creates an animation range
  50904. * @param name Name of the animation range
  50905. * @param from Starting frame of the animation range
  50906. * @param to Ending frame of the animation
  50907. */
  50908. Animation.prototype.createRange = function (name, from, to) {
  50909. // check name not already in use; could happen for bones after serialized
  50910. if (!this._ranges[name]) {
  50911. this._ranges[name] = new AnimationRange(name, from, to);
  50912. }
  50913. };
  50914. /**
  50915. * Deletes an animation range by name
  50916. * @param name Name of the animation range to delete
  50917. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50918. */
  50919. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50920. if (deleteFrames === void 0) { deleteFrames = true; }
  50921. var range = this._ranges[name];
  50922. if (!range) {
  50923. return;
  50924. }
  50925. if (deleteFrames) {
  50926. var from = range.from;
  50927. var to = range.to;
  50928. // this loop MUST go high to low for multiple splices to work
  50929. for (var key = this._keys.length - 1; key >= 0; key--) {
  50930. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50931. this._keys.splice(key, 1);
  50932. }
  50933. }
  50934. }
  50935. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50936. };
  50937. /**
  50938. * Gets the animation range by name, or null if not defined
  50939. * @param name Name of the animation range
  50940. * @returns Nullable animation range
  50941. */
  50942. Animation.prototype.getRange = function (name) {
  50943. return this._ranges[name];
  50944. };
  50945. /**
  50946. * Gets the key frames from the animation
  50947. * @returns The key frames of the animation
  50948. */
  50949. Animation.prototype.getKeys = function () {
  50950. return this._keys;
  50951. };
  50952. /**
  50953. * Gets the highest frame rate of the animation
  50954. * @returns Highest frame rate of the animation
  50955. */
  50956. Animation.prototype.getHighestFrame = function () {
  50957. var ret = 0;
  50958. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50959. if (ret < this._keys[key].frame) {
  50960. ret = this._keys[key].frame;
  50961. }
  50962. }
  50963. return ret;
  50964. };
  50965. /**
  50966. * Gets the easing function of the animation
  50967. * @returns Easing function of the animation
  50968. */
  50969. Animation.prototype.getEasingFunction = function () {
  50970. return this._easingFunction;
  50971. };
  50972. /**
  50973. * Sets the easing function of the animation
  50974. * @param easingFunction A custom mathematical formula for animation
  50975. */
  50976. Animation.prototype.setEasingFunction = function (easingFunction) {
  50977. this._easingFunction = easingFunction;
  50978. };
  50979. /**
  50980. * Interpolates a scalar linearly
  50981. * @param startValue Start value of the animation curve
  50982. * @param endValue End value of the animation curve
  50983. * @param gradient Scalar amount to interpolate
  50984. * @returns Interpolated scalar value
  50985. */
  50986. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50987. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50988. };
  50989. /**
  50990. * Interpolates a scalar cubically
  50991. * @param startValue Start value of the animation curve
  50992. * @param outTangent End tangent of the animation
  50993. * @param endValue End value of the animation curve
  50994. * @param inTangent Start tangent of the animation curve
  50995. * @param gradient Scalar amount to interpolate
  50996. * @returns Interpolated scalar value
  50997. */
  50998. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50999. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51000. };
  51001. /**
  51002. * Interpolates a quaternion using a spherical linear interpolation
  51003. * @param startValue Start value of the animation curve
  51004. * @param endValue End value of the animation curve
  51005. * @param gradient Scalar amount to interpolate
  51006. * @returns Interpolated quaternion value
  51007. */
  51008. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51009. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51010. };
  51011. /**
  51012. * Interpolates a quaternion cubically
  51013. * @param startValue Start value of the animation curve
  51014. * @param outTangent End tangent of the animation curve
  51015. * @param endValue End value of the animation curve
  51016. * @param inTangent Start tangent of the animation curve
  51017. * @param gradient Scalar amount to interpolate
  51018. * @returns Interpolated quaternion value
  51019. */
  51020. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51021. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51022. };
  51023. /**
  51024. * Interpolates a Vector3 linearl
  51025. * @param startValue Start value of the animation curve
  51026. * @param endValue End value of the animation curve
  51027. * @param gradient Scalar amount to interpolate
  51028. * @returns Interpolated scalar value
  51029. */
  51030. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51031. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51032. };
  51033. /**
  51034. * Interpolates a Vector3 cubically
  51035. * @param startValue Start value of the animation curve
  51036. * @param outTangent End tangent of the animation
  51037. * @param endValue End value of the animation curve
  51038. * @param inTangent Start tangent of the animation curve
  51039. * @param gradient Scalar amount to interpolate
  51040. * @returns InterpolatedVector3 value
  51041. */
  51042. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51043. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51044. };
  51045. /**
  51046. * Interpolates a Vector2 linearly
  51047. * @param startValue Start value of the animation curve
  51048. * @param endValue End value of the animation curve
  51049. * @param gradient Scalar amount to interpolate
  51050. * @returns Interpolated Vector2 value
  51051. */
  51052. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51053. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51054. };
  51055. /**
  51056. * Interpolates a Vector2 cubically
  51057. * @param startValue Start value of the animation curve
  51058. * @param outTangent End tangent of the animation
  51059. * @param endValue End value of the animation curve
  51060. * @param inTangent Start tangent of the animation curve
  51061. * @param gradient Scalar amount to interpolate
  51062. * @returns Interpolated Vector2 value
  51063. */
  51064. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51065. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51066. };
  51067. /**
  51068. * Interpolates a size linearly
  51069. * @param startValue Start value of the animation curve
  51070. * @param endValue End value of the animation curve
  51071. * @param gradient Scalar amount to interpolate
  51072. * @returns Interpolated Size value
  51073. */
  51074. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51075. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51076. };
  51077. /**
  51078. * Interpolates a Color3 linearly
  51079. * @param startValue Start value of the animation curve
  51080. * @param endValue End value of the animation curve
  51081. * @param gradient Scalar amount to interpolate
  51082. * @returns Interpolated Color3 value
  51083. */
  51084. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51085. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51086. };
  51087. /**
  51088. * @hidden Internal use only
  51089. */
  51090. Animation.prototype._getKeyValue = function (value) {
  51091. if (typeof value === "function") {
  51092. return value();
  51093. }
  51094. return value;
  51095. };
  51096. /**
  51097. * @hidden Internal use only
  51098. */
  51099. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51100. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51101. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51102. }
  51103. var keys = this.getKeys();
  51104. // Try to get a hash to find the right key
  51105. 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));
  51106. if (keys[startKeyIndex].frame >= currentFrame) {
  51107. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51108. startKeyIndex--;
  51109. }
  51110. }
  51111. for (var key = startKeyIndex; key < keys.length; key++) {
  51112. var endKey = keys[key + 1];
  51113. if (endKey.frame >= currentFrame) {
  51114. var startKey = keys[key];
  51115. var startValue = this._getKeyValue(startKey.value);
  51116. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51117. return startValue;
  51118. }
  51119. var endValue = this._getKeyValue(endKey.value);
  51120. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51121. var frameDelta = endKey.frame - startKey.frame;
  51122. // gradient : percent of currentFrame between the frame inf and the frame sup
  51123. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51124. // check for easingFunction and correction of gradient
  51125. var easingFunction = this.getEasingFunction();
  51126. if (easingFunction != null) {
  51127. gradient = easingFunction.ease(gradient);
  51128. }
  51129. switch (this.dataType) {
  51130. // Float
  51131. case Animation.ANIMATIONTYPE_FLOAT:
  51132. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51133. switch (loopMode) {
  51134. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51135. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51136. return floatValue;
  51137. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51138. return offsetValue * repeatCount + floatValue;
  51139. }
  51140. break;
  51141. // Quaternion
  51142. case Animation.ANIMATIONTYPE_QUATERNION:
  51143. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51144. switch (loopMode) {
  51145. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51146. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51147. return quatValue;
  51148. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51149. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51150. }
  51151. return quatValue;
  51152. // Vector3
  51153. case Animation.ANIMATIONTYPE_VECTOR3:
  51154. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51155. switch (loopMode) {
  51156. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51157. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51158. return vec3Value;
  51159. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51160. return vec3Value.add(offsetValue.scale(repeatCount));
  51161. }
  51162. // Vector2
  51163. case Animation.ANIMATIONTYPE_VECTOR2:
  51164. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51165. switch (loopMode) {
  51166. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51167. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51168. return vec2Value;
  51169. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51170. return vec2Value.add(offsetValue.scale(repeatCount));
  51171. }
  51172. // Size
  51173. case Animation.ANIMATIONTYPE_SIZE:
  51174. switch (loopMode) {
  51175. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51176. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51177. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51178. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51179. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51180. }
  51181. // Color3
  51182. case Animation.ANIMATIONTYPE_COLOR3:
  51183. switch (loopMode) {
  51184. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51185. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51186. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51187. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51188. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51189. }
  51190. // Matrix
  51191. case Animation.ANIMATIONTYPE_MATRIX:
  51192. switch (loopMode) {
  51193. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51194. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51195. if (Animation.AllowMatricesInterpolation) {
  51196. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51197. }
  51198. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51199. return startValue;
  51200. }
  51201. default:
  51202. break;
  51203. }
  51204. break;
  51205. }
  51206. }
  51207. return this._getKeyValue(keys[keys.length - 1].value);
  51208. };
  51209. /**
  51210. * Defines the function to use to interpolate matrices
  51211. * @param startValue defines the start matrix
  51212. * @param endValue defines the end matrix
  51213. * @param gradient defines the gradient between both matrices
  51214. * @param result defines an optional target matrix where to store the interpolation
  51215. * @returns the interpolated matrix
  51216. */
  51217. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51218. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51219. if (result) {
  51220. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51221. return result;
  51222. }
  51223. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51224. }
  51225. if (result) {
  51226. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51227. return result;
  51228. }
  51229. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51230. };
  51231. /**
  51232. * Makes a copy of the animation
  51233. * @returns Cloned animation
  51234. */
  51235. Animation.prototype.clone = function () {
  51236. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51237. clone.enableBlending = this.enableBlending;
  51238. clone.blendingSpeed = this.blendingSpeed;
  51239. if (this._keys) {
  51240. clone.setKeys(this._keys);
  51241. }
  51242. if (this._ranges) {
  51243. clone._ranges = {};
  51244. for (var name in this._ranges) {
  51245. var range = this._ranges[name];
  51246. if (!range) {
  51247. continue;
  51248. }
  51249. clone._ranges[name] = range.clone();
  51250. }
  51251. }
  51252. return clone;
  51253. };
  51254. /**
  51255. * Sets the key frames of the animation
  51256. * @param values The animation key frames to set
  51257. */
  51258. Animation.prototype.setKeys = function (values) {
  51259. this._keys = values.slice(0);
  51260. };
  51261. /**
  51262. * Serializes the animation to an object
  51263. * @returns Serialized object
  51264. */
  51265. Animation.prototype.serialize = function () {
  51266. var serializationObject = {};
  51267. serializationObject.name = this.name;
  51268. serializationObject.property = this.targetProperty;
  51269. serializationObject.framePerSecond = this.framePerSecond;
  51270. serializationObject.dataType = this.dataType;
  51271. serializationObject.loopBehavior = this.loopMode;
  51272. serializationObject.enableBlending = this.enableBlending;
  51273. serializationObject.blendingSpeed = this.blendingSpeed;
  51274. var dataType = this.dataType;
  51275. serializationObject.keys = [];
  51276. var keys = this.getKeys();
  51277. for (var index = 0; index < keys.length; index++) {
  51278. var animationKey = keys[index];
  51279. var key = {};
  51280. key.frame = animationKey.frame;
  51281. switch (dataType) {
  51282. case Animation.ANIMATIONTYPE_FLOAT:
  51283. key.values = [animationKey.value];
  51284. break;
  51285. case Animation.ANIMATIONTYPE_QUATERNION:
  51286. case Animation.ANIMATIONTYPE_MATRIX:
  51287. case Animation.ANIMATIONTYPE_VECTOR3:
  51288. case Animation.ANIMATIONTYPE_COLOR3:
  51289. key.values = animationKey.value.asArray();
  51290. break;
  51291. }
  51292. serializationObject.keys.push(key);
  51293. }
  51294. serializationObject.ranges = [];
  51295. for (var name in this._ranges) {
  51296. var source = this._ranges[name];
  51297. if (!source) {
  51298. continue;
  51299. }
  51300. var range = {};
  51301. range.name = name;
  51302. range.from = source.from;
  51303. range.to = source.to;
  51304. serializationObject.ranges.push(range);
  51305. }
  51306. return serializationObject;
  51307. };
  51308. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51309. /**
  51310. * Get the float animation type
  51311. */
  51312. get: function () {
  51313. return Animation._ANIMATIONTYPE_FLOAT;
  51314. },
  51315. enumerable: true,
  51316. configurable: true
  51317. });
  51318. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51319. /**
  51320. * Get the Vector3 animation type
  51321. */
  51322. get: function () {
  51323. return Animation._ANIMATIONTYPE_VECTOR3;
  51324. },
  51325. enumerable: true,
  51326. configurable: true
  51327. });
  51328. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51329. /**
  51330. * Get the Vectpr2 animation type
  51331. */
  51332. get: function () {
  51333. return Animation._ANIMATIONTYPE_VECTOR2;
  51334. },
  51335. enumerable: true,
  51336. configurable: true
  51337. });
  51338. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51339. /**
  51340. * Get the Size animation type
  51341. */
  51342. get: function () {
  51343. return Animation._ANIMATIONTYPE_SIZE;
  51344. },
  51345. enumerable: true,
  51346. configurable: true
  51347. });
  51348. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51349. /**
  51350. * Get the Quaternion animation type
  51351. */
  51352. get: function () {
  51353. return Animation._ANIMATIONTYPE_QUATERNION;
  51354. },
  51355. enumerable: true,
  51356. configurable: true
  51357. });
  51358. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51359. /**
  51360. * Get the Matrix animation type
  51361. */
  51362. get: function () {
  51363. return Animation._ANIMATIONTYPE_MATRIX;
  51364. },
  51365. enumerable: true,
  51366. configurable: true
  51367. });
  51368. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51369. /**
  51370. * Get the Color3 animation type
  51371. */
  51372. get: function () {
  51373. return Animation._ANIMATIONTYPE_COLOR3;
  51374. },
  51375. enumerable: true,
  51376. configurable: true
  51377. });
  51378. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51379. /**
  51380. * Get the Relative Loop Mode
  51381. */
  51382. get: function () {
  51383. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51384. },
  51385. enumerable: true,
  51386. configurable: true
  51387. });
  51388. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51389. /**
  51390. * Get the Cycle Loop Mode
  51391. */
  51392. get: function () {
  51393. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51394. },
  51395. enumerable: true,
  51396. configurable: true
  51397. });
  51398. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51399. /**
  51400. * Get the Constant Loop Mode
  51401. */
  51402. get: function () {
  51403. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51404. },
  51405. enumerable: true,
  51406. configurable: true
  51407. });
  51408. /** @hidden */
  51409. Animation._UniversalLerp = function (left, right, amount) {
  51410. var constructor = left.constructor;
  51411. if (constructor.Lerp) { // Lerp supported
  51412. return constructor.Lerp(left, right, amount);
  51413. }
  51414. else if (constructor.Slerp) { // Slerp supported
  51415. return constructor.Slerp(left, right, amount);
  51416. }
  51417. else if (left.toFixed) { // Number
  51418. return left * (1.0 - amount) + amount * right;
  51419. }
  51420. else { // Blending not supported
  51421. return right;
  51422. }
  51423. };
  51424. /**
  51425. * Parses an animation object and creates an animation
  51426. * @param parsedAnimation Parsed animation object
  51427. * @returns Animation object
  51428. */
  51429. Animation.Parse = function (parsedAnimation) {
  51430. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51431. var dataType = parsedAnimation.dataType;
  51432. var keys = [];
  51433. var data;
  51434. var index;
  51435. if (parsedAnimation.enableBlending) {
  51436. animation.enableBlending = parsedAnimation.enableBlending;
  51437. }
  51438. if (parsedAnimation.blendingSpeed) {
  51439. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51440. }
  51441. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51442. var key = parsedAnimation.keys[index];
  51443. var inTangent;
  51444. var outTangent;
  51445. switch (dataType) {
  51446. case Animation.ANIMATIONTYPE_FLOAT:
  51447. data = key.values[0];
  51448. if (key.values.length >= 1) {
  51449. inTangent = key.values[1];
  51450. }
  51451. if (key.values.length >= 2) {
  51452. outTangent = key.values[2];
  51453. }
  51454. break;
  51455. case Animation.ANIMATIONTYPE_QUATERNION:
  51456. data = BABYLON.Quaternion.FromArray(key.values);
  51457. if (key.values.length >= 8) {
  51458. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51459. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51460. inTangent = _inTangent;
  51461. }
  51462. }
  51463. if (key.values.length >= 12) {
  51464. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51465. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51466. outTangent = _outTangent;
  51467. }
  51468. }
  51469. break;
  51470. case Animation.ANIMATIONTYPE_MATRIX:
  51471. data = BABYLON.Matrix.FromArray(key.values);
  51472. break;
  51473. case Animation.ANIMATIONTYPE_COLOR3:
  51474. data = BABYLON.Color3.FromArray(key.values);
  51475. break;
  51476. case Animation.ANIMATIONTYPE_VECTOR3:
  51477. default:
  51478. data = BABYLON.Vector3.FromArray(key.values);
  51479. break;
  51480. }
  51481. var keyData = {};
  51482. keyData.frame = key.frame;
  51483. keyData.value = data;
  51484. if (inTangent != undefined) {
  51485. keyData.inTangent = inTangent;
  51486. }
  51487. if (outTangent != undefined) {
  51488. keyData.outTangent = outTangent;
  51489. }
  51490. keys.push(keyData);
  51491. }
  51492. animation.setKeys(keys);
  51493. if (parsedAnimation.ranges) {
  51494. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51495. data = parsedAnimation.ranges[index];
  51496. animation.createRange(data.name, data.from, data.to);
  51497. }
  51498. }
  51499. return animation;
  51500. };
  51501. /**
  51502. * Appends the serialized animations from the source animations
  51503. * @param source Source containing the animations
  51504. * @param destination Target to store the animations
  51505. */
  51506. Animation.AppendSerializedAnimations = function (source, destination) {
  51507. if (source.animations) {
  51508. destination.animations = [];
  51509. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51510. var animation = source.animations[animationIndex];
  51511. destination.animations.push(animation.serialize());
  51512. }
  51513. }
  51514. };
  51515. /**
  51516. * Use matrix interpolation instead of using direct key value when animating matrices
  51517. */
  51518. Animation.AllowMatricesInterpolation = false;
  51519. /**
  51520. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51521. */
  51522. Animation.AllowMatrixDecomposeForInterpolation = true;
  51523. // Statics
  51524. /**
  51525. * Float animation type
  51526. */
  51527. Animation._ANIMATIONTYPE_FLOAT = 0;
  51528. /**
  51529. * Vector3 animation type
  51530. */
  51531. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51532. /**
  51533. * Quaternion animation type
  51534. */
  51535. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51536. /**
  51537. * Matrix animation type
  51538. */
  51539. Animation._ANIMATIONTYPE_MATRIX = 3;
  51540. /**
  51541. * Color3 animation type
  51542. */
  51543. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51544. /**
  51545. * Vector2 animation type
  51546. */
  51547. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51548. /**
  51549. * Size animation type
  51550. */
  51551. Animation._ANIMATIONTYPE_SIZE = 6;
  51552. /**
  51553. * Relative Loop Mode
  51554. */
  51555. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51556. /**
  51557. * Cycle Loop Mode
  51558. */
  51559. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51560. /**
  51561. * Constant Loop Mode
  51562. */
  51563. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51564. return Animation;
  51565. }());
  51566. BABYLON.Animation = Animation;
  51567. })(BABYLON || (BABYLON = {}));
  51568. //# sourceMappingURL=babylon.animation.js.map
  51569. var BABYLON;
  51570. (function (BABYLON) {
  51571. /**
  51572. * This class defines the direct association between an animation and a target
  51573. */
  51574. var TargetedAnimation = /** @class */ (function () {
  51575. function TargetedAnimation() {
  51576. }
  51577. return TargetedAnimation;
  51578. }());
  51579. BABYLON.TargetedAnimation = TargetedAnimation;
  51580. /**
  51581. * Use this class to create coordinated animations on multiple targets
  51582. */
  51583. var AnimationGroup = /** @class */ (function () {
  51584. function AnimationGroup(name, scene) {
  51585. if (scene === void 0) { scene = null; }
  51586. this.name = name;
  51587. this._targetedAnimations = new Array();
  51588. this._animatables = new Array();
  51589. this._from = Number.MAX_VALUE;
  51590. this._to = -Number.MAX_VALUE;
  51591. this._speedRatio = 1;
  51592. this.onAnimationEndObservable = new BABYLON.Observable();
  51593. /**
  51594. * This observable will notify when all animations have ended.
  51595. */
  51596. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51597. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51598. this._scene.animationGroups.push(this);
  51599. }
  51600. Object.defineProperty(AnimationGroup.prototype, "from", {
  51601. /**
  51602. * Gets the first frame
  51603. */
  51604. get: function () {
  51605. return this._from;
  51606. },
  51607. enumerable: true,
  51608. configurable: true
  51609. });
  51610. Object.defineProperty(AnimationGroup.prototype, "to", {
  51611. /**
  51612. * Gets the last frame
  51613. */
  51614. get: function () {
  51615. return this._to;
  51616. },
  51617. enumerable: true,
  51618. configurable: true
  51619. });
  51620. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51621. /**
  51622. * Define if the animations are started
  51623. */
  51624. get: function () {
  51625. return this._isStarted;
  51626. },
  51627. enumerable: true,
  51628. configurable: true
  51629. });
  51630. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51631. /**
  51632. * Gets or sets the speed ratio to use for all animations
  51633. */
  51634. get: function () {
  51635. return this._speedRatio;
  51636. },
  51637. /**
  51638. * Gets or sets the speed ratio to use for all animations
  51639. */
  51640. set: function (value) {
  51641. if (this._speedRatio === value) {
  51642. return;
  51643. }
  51644. this._speedRatio = value;
  51645. for (var index = 0; index < this._animatables.length; index++) {
  51646. var animatable = this._animatables[index];
  51647. animatable.speedRatio = this._speedRatio;
  51648. }
  51649. },
  51650. enumerable: true,
  51651. configurable: true
  51652. });
  51653. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51654. /**
  51655. * Gets the targeted animations for this animation group
  51656. */
  51657. get: function () {
  51658. return this._targetedAnimations;
  51659. },
  51660. enumerable: true,
  51661. configurable: true
  51662. });
  51663. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51664. /**
  51665. * returning the list of animatables controlled by this animation group.
  51666. */
  51667. get: function () {
  51668. return this._animatables;
  51669. },
  51670. enumerable: true,
  51671. configurable: true
  51672. });
  51673. /**
  51674. * Add an animation (with its target) in the group
  51675. * @param animation defines the animation we want to add
  51676. * @param target defines the target of the animation
  51677. * @returns the {BABYLON.TargetedAnimation} object
  51678. */
  51679. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51680. var targetedAnimation = {
  51681. animation: animation,
  51682. target: target
  51683. };
  51684. var keys = animation.getKeys();
  51685. if (this._from > keys[0].frame) {
  51686. this._from = keys[0].frame;
  51687. }
  51688. if (this._to < keys[keys.length - 1].frame) {
  51689. this._to = keys[keys.length - 1].frame;
  51690. }
  51691. this._targetedAnimations.push(targetedAnimation);
  51692. return targetedAnimation;
  51693. };
  51694. /**
  51695. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51696. * It can add constant keys at begin or end
  51697. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51698. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51699. */
  51700. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51701. if (beginFrame === void 0) { beginFrame = null; }
  51702. if (endFrame === void 0) { endFrame = null; }
  51703. if (beginFrame == null)
  51704. beginFrame = this._from;
  51705. if (endFrame == null)
  51706. endFrame = this._to;
  51707. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51708. var targetedAnimation = this._targetedAnimations[index];
  51709. var keys = targetedAnimation.animation.getKeys();
  51710. var startKey = keys[0];
  51711. var endKey = keys[keys.length - 1];
  51712. if (startKey.frame > beginFrame) {
  51713. var newKey = {
  51714. frame: beginFrame,
  51715. value: startKey.value,
  51716. inTangent: startKey.inTangent,
  51717. outTangent: startKey.outTangent,
  51718. interpolation: startKey.interpolation
  51719. };
  51720. keys.splice(0, 0, newKey);
  51721. }
  51722. if (endKey.frame < endFrame) {
  51723. var newKey = {
  51724. frame: endFrame,
  51725. value: endKey.value,
  51726. inTangent: endKey.outTangent,
  51727. outTangent: endKey.outTangent,
  51728. interpolation: endKey.interpolation
  51729. };
  51730. keys.push(newKey);
  51731. }
  51732. }
  51733. this._from = beginFrame;
  51734. this._to = endFrame;
  51735. return this;
  51736. };
  51737. /**
  51738. * Start all animations on given targets
  51739. * @param loop defines if animations must loop
  51740. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51741. * @param from defines the from key (optional)
  51742. * @param to defines the to key (optional)
  51743. * @returns the current animation group
  51744. */
  51745. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51746. var _this = this;
  51747. if (loop === void 0) { loop = false; }
  51748. if (speedRatio === void 0) { speedRatio = 1; }
  51749. if (this._isStarted || this._targetedAnimations.length === 0) {
  51750. return this;
  51751. }
  51752. var _loop_1 = function (targetedAnimation) {
  51753. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51754. animatable.onAnimationEnd = function () {
  51755. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51756. _this._checkAnimationGroupEnded(animatable);
  51757. };
  51758. this_1._animatables.push(animatable);
  51759. };
  51760. var this_1 = this;
  51761. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51762. var targetedAnimation = _a[_i];
  51763. _loop_1(targetedAnimation);
  51764. }
  51765. this._speedRatio = speedRatio;
  51766. this._isStarted = true;
  51767. return this;
  51768. };
  51769. /**
  51770. * Pause all animations
  51771. */
  51772. AnimationGroup.prototype.pause = function () {
  51773. if (!this._isStarted) {
  51774. return this;
  51775. }
  51776. for (var index = 0; index < this._animatables.length; index++) {
  51777. var animatable = this._animatables[index];
  51778. animatable.pause();
  51779. }
  51780. return this;
  51781. };
  51782. /**
  51783. * Play all animations to initial state
  51784. * This function will start() the animations if they were not started or will restart() them if they were paused
  51785. * @param loop defines if animations must loop
  51786. */
  51787. AnimationGroup.prototype.play = function (loop) {
  51788. // only if all animatables are ready and exist
  51789. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51790. if (loop !== undefined) {
  51791. for (var index = 0; index < this._animatables.length; index++) {
  51792. var animatable = this._animatables[index];
  51793. animatable.loopAnimation = loop;
  51794. }
  51795. }
  51796. this.restart();
  51797. }
  51798. else {
  51799. this.stop();
  51800. this.start(loop, this._speedRatio);
  51801. }
  51802. return this;
  51803. };
  51804. /**
  51805. * Reset all animations to initial state
  51806. */
  51807. AnimationGroup.prototype.reset = function () {
  51808. if (!this._isStarted) {
  51809. return this;
  51810. }
  51811. for (var index = 0; index < this._animatables.length; index++) {
  51812. var animatable = this._animatables[index];
  51813. animatable.reset();
  51814. }
  51815. return this;
  51816. };
  51817. /**
  51818. * Restart animations from key 0
  51819. */
  51820. AnimationGroup.prototype.restart = function () {
  51821. if (!this._isStarted) {
  51822. return this;
  51823. }
  51824. for (var index = 0; index < this._animatables.length; index++) {
  51825. var animatable = this._animatables[index];
  51826. animatable.restart();
  51827. }
  51828. return this;
  51829. };
  51830. /**
  51831. * Stop all animations
  51832. */
  51833. AnimationGroup.prototype.stop = function () {
  51834. if (!this._isStarted) {
  51835. return this;
  51836. }
  51837. for (var index = 0; index < this._animatables.length; index++) {
  51838. var animatable = this._animatables[index];
  51839. animatable.stop();
  51840. }
  51841. this._isStarted = false;
  51842. return this;
  51843. };
  51844. /**
  51845. * Set animation weight for all animatables
  51846. * @param weight defines the weight to use
  51847. * @return the animationGroup
  51848. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51849. */
  51850. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51851. for (var index = 0; index < this._animatables.length; index++) {
  51852. var animatable = this._animatables[index];
  51853. animatable.weight = weight;
  51854. }
  51855. return this;
  51856. };
  51857. /**
  51858. * Synchronize and normalize all animatables with a source animatable
  51859. * @param root defines the root animatable to synchronize with
  51860. * @return the animationGroup
  51861. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51862. */
  51863. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51864. for (var index = 0; index < this._animatables.length; index++) {
  51865. var animatable = this._animatables[index];
  51866. animatable.syncWith(root);
  51867. }
  51868. return this;
  51869. };
  51870. /**
  51871. * Goes to a specific frame in this animation group
  51872. * @param frame the frame number to go to
  51873. * @return the animationGroup
  51874. */
  51875. AnimationGroup.prototype.goToFrame = function (frame) {
  51876. if (!this._isStarted) {
  51877. return this;
  51878. }
  51879. for (var index = 0; index < this._animatables.length; index++) {
  51880. var animatable = this._animatables[index];
  51881. animatable.goToFrame(frame);
  51882. }
  51883. return this;
  51884. };
  51885. /**
  51886. * Dispose all associated resources
  51887. */
  51888. AnimationGroup.prototype.dispose = function () {
  51889. this._targetedAnimations = [];
  51890. this._animatables = [];
  51891. var index = this._scene.animationGroups.indexOf(this);
  51892. if (index > -1) {
  51893. this._scene.animationGroups.splice(index, 1);
  51894. }
  51895. };
  51896. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51897. // animatable should be taken out of the array
  51898. var idx = this._animatables.indexOf(animatable);
  51899. if (idx > -1) {
  51900. this._animatables.splice(idx, 1);
  51901. }
  51902. // all animatables were removed? animation group ended!
  51903. if (this._animatables.length === 0) {
  51904. this._isStarted = false;
  51905. this.onAnimationGroupEndObservable.notifyObservers(this);
  51906. }
  51907. };
  51908. return AnimationGroup;
  51909. }());
  51910. BABYLON.AnimationGroup = AnimationGroup;
  51911. })(BABYLON || (BABYLON = {}));
  51912. //# sourceMappingURL=babylon.animationGroup.js.map
  51913. var BABYLON;
  51914. (function (BABYLON) {
  51915. /**
  51916. * Defines a runtime animation
  51917. */
  51918. var RuntimeAnimation = /** @class */ (function () {
  51919. /**
  51920. * Create a new RuntimeAnimation object
  51921. * @param target defines the target of the animation
  51922. * @param animation defines the source animation object
  51923. * @param scene defines the hosting scene
  51924. * @param host defines the initiating Animatable
  51925. */
  51926. function RuntimeAnimation(target, animation, scene, host) {
  51927. var _this = this;
  51928. this._events = new Array();
  51929. /**
  51930. * The current frame of the runtime animation
  51931. */
  51932. this._currentFrame = 0;
  51933. /**
  51934. * The original value of the runtime animation
  51935. */
  51936. this._originalValue = new Array();
  51937. /**
  51938. * The offsets cache of the runtime animation
  51939. */
  51940. this._offsetsCache = {};
  51941. /**
  51942. * The high limits cache of the runtime animation
  51943. */
  51944. this._highLimitsCache = {};
  51945. /**
  51946. * Specifies if the runtime animation has been stopped
  51947. */
  51948. this._stopped = false;
  51949. /**
  51950. * The blending factor of the runtime animation
  51951. */
  51952. this._blendingFactor = 0;
  51953. /**
  51954. * The target path of the runtime animation
  51955. */
  51956. this._targetPath = "";
  51957. /**
  51958. * The weight of the runtime animation
  51959. */
  51960. this._weight = 1.0;
  51961. /**
  51962. * The ratio offset of the runtime animation
  51963. */
  51964. this._ratioOffset = 0;
  51965. /**
  51966. * The previous delay of the runtime animation
  51967. */
  51968. this._previousDelay = 0;
  51969. /**
  51970. * The previous ratio of the runtime animation
  51971. */
  51972. this._previousRatio = 0;
  51973. this._animation = animation;
  51974. this._target = target;
  51975. this._scene = scene;
  51976. this._host = host;
  51977. animation._runtimeAnimations.push(this);
  51978. // Cloning events locally
  51979. var events = animation.getEvents();
  51980. if (events && events.length > 0) {
  51981. events.forEach(function (e) {
  51982. _this._events.push(e._clone());
  51983. });
  51984. }
  51985. }
  51986. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51987. /**
  51988. * Gets the current frame of the runtime animation
  51989. */
  51990. get: function () {
  51991. return this._currentFrame;
  51992. },
  51993. enumerable: true,
  51994. configurable: true
  51995. });
  51996. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51997. /**
  51998. * Gets the weight of the runtime animation
  51999. */
  52000. get: function () {
  52001. return this._weight;
  52002. },
  52003. enumerable: true,
  52004. configurable: true
  52005. });
  52006. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52007. /**
  52008. * Gets the current value of the runtime animation
  52009. */
  52010. get: function () {
  52011. return this._currentValue;
  52012. },
  52013. enumerable: true,
  52014. configurable: true
  52015. });
  52016. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52017. /**
  52018. * Gets the target path of the runtime animation
  52019. */
  52020. get: function () {
  52021. return this._targetPath;
  52022. },
  52023. enumerable: true,
  52024. configurable: true
  52025. });
  52026. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52027. /**
  52028. * Gets the actual target of the runtime animation
  52029. */
  52030. get: function () {
  52031. return this._activeTarget;
  52032. },
  52033. enumerable: true,
  52034. configurable: true
  52035. });
  52036. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52037. /**
  52038. * Gets the animation from the runtime animation
  52039. */
  52040. get: function () {
  52041. return this._animation;
  52042. },
  52043. enumerable: true,
  52044. configurable: true
  52045. });
  52046. /**
  52047. * Resets the runtime animation to the beginning
  52048. * @param restoreOriginal defines whether to restore the target property to the original value
  52049. */
  52050. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52051. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52052. if (restoreOriginal) {
  52053. if (this._target instanceof Array) {
  52054. var index = 0;
  52055. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52056. var target = _a[_i];
  52057. if (this._originalValue[index] !== undefined) {
  52058. this._setValue(target, this._originalValue[index], -1);
  52059. }
  52060. index++;
  52061. }
  52062. }
  52063. else {
  52064. if (this._originalValue[0] !== undefined) {
  52065. this._setValue(this._target, this._originalValue[0], -1);
  52066. }
  52067. }
  52068. }
  52069. this._offsetsCache = {};
  52070. this._highLimitsCache = {};
  52071. this._currentFrame = 0;
  52072. this._blendingFactor = 0;
  52073. this._originalValue = new Array();
  52074. // Events
  52075. for (var index = 0; index < this._events.length; index++) {
  52076. this._events[index].isDone = false;
  52077. }
  52078. };
  52079. /**
  52080. * Specifies if the runtime animation is stopped
  52081. * @returns Boolean specifying if the runtime animation is stopped
  52082. */
  52083. RuntimeAnimation.prototype.isStopped = function () {
  52084. return this._stopped;
  52085. };
  52086. /**
  52087. * Disposes of the runtime animation
  52088. */
  52089. RuntimeAnimation.prototype.dispose = function () {
  52090. var index = this._animation.runtimeAnimations.indexOf(this);
  52091. if (index > -1) {
  52092. this._animation.runtimeAnimations.splice(index, 1);
  52093. }
  52094. };
  52095. /**
  52096. * Interpolates the animation from the current frame
  52097. * @param currentFrame The frame to interpolate the animation to
  52098. * @param repeatCount The number of times that the animation should loop
  52099. * @param loopMode The type of looping mode to use
  52100. * @param offsetValue Animation offset value
  52101. * @param highLimitValue The high limit value
  52102. * @returns The interpolated value
  52103. */
  52104. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52105. this._currentFrame = currentFrame;
  52106. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52107. this._workValue = BABYLON.Matrix.Zero();
  52108. }
  52109. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52110. };
  52111. /**
  52112. * Apply the interpolated value to the target
  52113. * @param currentValue defines the value computed by the animation
  52114. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52115. */
  52116. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52117. if (weight === void 0) { weight = 1.0; }
  52118. if (this._target instanceof Array) {
  52119. var index = 0;
  52120. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52121. var target = _a[_i];
  52122. this._setValue(target, currentValue, weight, index);
  52123. index++;
  52124. }
  52125. }
  52126. else {
  52127. this._setValue(this._target, currentValue, weight);
  52128. }
  52129. };
  52130. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52131. if (targetIndex === void 0) { targetIndex = 0; }
  52132. // Set value
  52133. var path;
  52134. var destination;
  52135. var targetPropertyPath = this._animation.targetPropertyPath;
  52136. if (targetPropertyPath.length > 1) {
  52137. var property = target[targetPropertyPath[0]];
  52138. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52139. property = property[targetPropertyPath[index]];
  52140. }
  52141. path = targetPropertyPath[targetPropertyPath.length - 1];
  52142. destination = property;
  52143. }
  52144. else {
  52145. path = targetPropertyPath[0];
  52146. destination = target;
  52147. }
  52148. this._targetPath = path;
  52149. this._activeTarget = destination;
  52150. this._weight = weight;
  52151. if (this._originalValue[targetIndex] === undefined) {
  52152. var originalValue = void 0;
  52153. if (destination.getRestPose && path === "_matrix") { // For bones
  52154. originalValue = destination.getRestPose();
  52155. }
  52156. else {
  52157. originalValue = destination[path];
  52158. }
  52159. if (originalValue && originalValue.clone) {
  52160. this._originalValue[targetIndex] = originalValue.clone();
  52161. }
  52162. else {
  52163. this._originalValue[targetIndex] = originalValue;
  52164. }
  52165. }
  52166. // Blending
  52167. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52168. if (enableBlending && this._blendingFactor <= 1.0) {
  52169. if (!this._originalBlendValue) {
  52170. var originalValue = destination[path];
  52171. if (originalValue.clone) {
  52172. this._originalBlendValue = originalValue.clone();
  52173. }
  52174. else {
  52175. this._originalBlendValue = originalValue;
  52176. }
  52177. }
  52178. if (this._originalBlendValue.m) { // Matrix
  52179. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52180. if (this._currentValue) {
  52181. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52182. }
  52183. else {
  52184. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52185. }
  52186. }
  52187. else {
  52188. if (this._currentValue) {
  52189. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52190. }
  52191. else {
  52192. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52193. }
  52194. }
  52195. }
  52196. else {
  52197. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52198. }
  52199. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52200. this._blendingFactor += blendingSpeed;
  52201. }
  52202. else {
  52203. this._currentValue = currentValue;
  52204. }
  52205. if (weight !== -1.0) {
  52206. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52207. }
  52208. else {
  52209. destination[path] = this._currentValue;
  52210. }
  52211. if (target.markAsDirty) {
  52212. target.markAsDirty(this._animation.targetProperty);
  52213. }
  52214. };
  52215. /**
  52216. * Gets the loop pmode of the runtime animation
  52217. * @returns Loop Mode
  52218. */
  52219. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52220. if (this._target && this._target.animationPropertiesOverride) {
  52221. return this._target.animationPropertiesOverride.loopMode;
  52222. }
  52223. return this._animation.loopMode;
  52224. };
  52225. /**
  52226. * Move the current animation to a given frame
  52227. * @param frame defines the frame to move to
  52228. */
  52229. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52230. var keys = this._animation.getKeys();
  52231. if (frame < keys[0].frame) {
  52232. frame = keys[0].frame;
  52233. }
  52234. else if (frame > keys[keys.length - 1].frame) {
  52235. frame = keys[keys.length - 1].frame;
  52236. }
  52237. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52238. this.setValue(currentValue, -1);
  52239. };
  52240. /**
  52241. * @hidden Internal use only
  52242. */
  52243. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52244. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52245. this._ratioOffset = this._previousRatio - newRatio;
  52246. };
  52247. /**
  52248. * Execute the current animation
  52249. * @param delay defines the delay to add to the current frame
  52250. * @param from defines the lower bound of the animation range
  52251. * @param to defines the upper bound of the animation range
  52252. * @param loop defines if the current animation must loop
  52253. * @param speedRatio defines the current speed ratio
  52254. * @param weight defines the weight of the animation (default is -1 so no weight)
  52255. * @returns a boolean indicating if the animation has ended
  52256. */
  52257. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52258. if (weight === void 0) { weight = -1.0; }
  52259. var targetPropertyPath = this._animation.targetPropertyPath;
  52260. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52261. this._stopped = true;
  52262. return false;
  52263. }
  52264. var returnValue = true;
  52265. var keys = this._animation.getKeys();
  52266. // Adding a start key at frame 0 if missing
  52267. if (keys[0].frame !== 0) {
  52268. var newKey = { frame: 0, value: keys[0].value };
  52269. keys.splice(0, 0, newKey);
  52270. }
  52271. // Check limits
  52272. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52273. from = keys[0].frame;
  52274. }
  52275. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52276. to = keys[keys.length - 1].frame;
  52277. }
  52278. //to and from cannot be the same key
  52279. if (from === to) {
  52280. if (from > keys[0].frame) {
  52281. from--;
  52282. }
  52283. else if (to < keys[keys.length - 1].frame) {
  52284. to++;
  52285. }
  52286. }
  52287. // Compute ratio
  52288. var range = to - from;
  52289. var offsetValue;
  52290. // ratio represents the frame delta between from and to
  52291. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52292. var highLimitValue = 0;
  52293. this._previousDelay = delay;
  52294. this._previousRatio = ratio;
  52295. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52296. returnValue = false;
  52297. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52298. }
  52299. else {
  52300. // Get max value if required
  52301. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52302. var keyOffset = to.toString() + from.toString();
  52303. if (!this._offsetsCache[keyOffset]) {
  52304. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52305. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52306. switch (this._animation.dataType) {
  52307. // Float
  52308. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52309. this._offsetsCache[keyOffset] = toValue - fromValue;
  52310. break;
  52311. // Quaternion
  52312. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52313. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52314. break;
  52315. // Vector3
  52316. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52317. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52318. // Vector2
  52319. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52320. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52321. // Size
  52322. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52323. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52324. // Color3
  52325. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52326. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52327. default:
  52328. break;
  52329. }
  52330. this._highLimitsCache[keyOffset] = toValue;
  52331. }
  52332. highLimitValue = this._highLimitsCache[keyOffset];
  52333. offsetValue = this._offsetsCache[keyOffset];
  52334. }
  52335. }
  52336. if (offsetValue === undefined) {
  52337. switch (this._animation.dataType) {
  52338. // Float
  52339. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52340. offsetValue = 0;
  52341. break;
  52342. // Quaternion
  52343. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52344. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52345. break;
  52346. // Vector3
  52347. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52348. offsetValue = BABYLON.Vector3.Zero();
  52349. break;
  52350. // Vector2
  52351. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52352. offsetValue = BABYLON.Vector2.Zero();
  52353. break;
  52354. // Size
  52355. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52356. offsetValue = BABYLON.Size.Zero();
  52357. break;
  52358. // Color3
  52359. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52360. offsetValue = BABYLON.Color3.Black();
  52361. }
  52362. }
  52363. // Compute value
  52364. var repeatCount = (ratio / range) >> 0;
  52365. var currentFrame = returnValue ? from + ratio % range : to;
  52366. // Need to normalize?
  52367. if (this._host && this._host.syncRoot) {
  52368. var syncRoot = this._host.syncRoot;
  52369. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52370. currentFrame = from + (to - from) * hostNormalizedFrame;
  52371. }
  52372. // Reset events if looping
  52373. var events = this._events;
  52374. if (range > 0 && this.currentFrame > currentFrame ||
  52375. range < 0 && this.currentFrame < currentFrame) {
  52376. // Need to reset animation events
  52377. for (var index = 0; index < events.length; index++) {
  52378. if (!events[index].onlyOnce) {
  52379. // reset event, the animation is looping
  52380. events[index].isDone = false;
  52381. }
  52382. }
  52383. }
  52384. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52385. // Set value
  52386. this.setValue(currentValue, weight);
  52387. // Check events
  52388. for (var index = 0; index < events.length; index++) {
  52389. // Make sure current frame has passed event frame and that event frame is within the current range
  52390. // Also, handle both forward and reverse animations
  52391. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52392. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52393. var event = events[index];
  52394. if (!event.isDone) {
  52395. // If event should be done only once, remove it.
  52396. if (event.onlyOnce) {
  52397. events.splice(index, 1);
  52398. index--;
  52399. }
  52400. event.isDone = true;
  52401. event.action();
  52402. } // Don't do anything if the event has already be done.
  52403. }
  52404. }
  52405. if (!returnValue) {
  52406. this._stopped = true;
  52407. }
  52408. return returnValue;
  52409. };
  52410. return RuntimeAnimation;
  52411. }());
  52412. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52413. })(BABYLON || (BABYLON = {}));
  52414. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52415. var BABYLON;
  52416. (function (BABYLON) {
  52417. var Animatable = /** @class */ (function () {
  52418. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52419. if (fromFrame === void 0) { fromFrame = 0; }
  52420. if (toFrame === void 0) { toFrame = 100; }
  52421. if (loopAnimation === void 0) { loopAnimation = false; }
  52422. if (speedRatio === void 0) { speedRatio = 1.0; }
  52423. this.target = target;
  52424. this.fromFrame = fromFrame;
  52425. this.toFrame = toFrame;
  52426. this.loopAnimation = loopAnimation;
  52427. this.onAnimationEnd = onAnimationEnd;
  52428. this._localDelayOffset = null;
  52429. this._pausedDelay = null;
  52430. this._runtimeAnimations = new Array();
  52431. this._paused = false;
  52432. this._speedRatio = 1;
  52433. this._weight = -1.0;
  52434. this.animationStarted = false;
  52435. /**
  52436. * Observer raised when the animation ends
  52437. */
  52438. this.onAnimationEndObservable = new BABYLON.Observable();
  52439. this._scene = scene;
  52440. if (animations) {
  52441. this.appendAnimations(target, animations);
  52442. }
  52443. this._speedRatio = speedRatio;
  52444. scene._activeAnimatables.push(this);
  52445. }
  52446. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52447. /**
  52448. * Gets the root Animatable used to synchronize and normalize animations
  52449. */
  52450. get: function () {
  52451. return this._syncRoot;
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52457. /**
  52458. * Gets the current frame of the first RuntimeAnimation
  52459. * Used to synchronize Animatables
  52460. */
  52461. get: function () {
  52462. if (this._runtimeAnimations.length === 0) {
  52463. return 0;
  52464. }
  52465. return this._runtimeAnimations[0].currentFrame;
  52466. },
  52467. enumerable: true,
  52468. configurable: true
  52469. });
  52470. Object.defineProperty(Animatable.prototype, "weight", {
  52471. /**
  52472. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52473. */
  52474. get: function () {
  52475. return this._weight;
  52476. },
  52477. set: function (value) {
  52478. if (value === -1) { // -1 is ok and means no weight
  52479. this._weight = -1;
  52480. return;
  52481. }
  52482. // Else weight must be in [0, 1] range
  52483. this._weight = Math.min(Math.max(value, 0), 1.0);
  52484. },
  52485. enumerable: true,
  52486. configurable: true
  52487. });
  52488. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52489. /**
  52490. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52491. */
  52492. get: function () {
  52493. return this._speedRatio;
  52494. },
  52495. set: function (value) {
  52496. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52497. var animation = this._runtimeAnimations[index];
  52498. animation._prepareForSpeedRatioChange(value);
  52499. }
  52500. this._speedRatio = value;
  52501. },
  52502. enumerable: true,
  52503. configurable: true
  52504. });
  52505. // Methods
  52506. /**
  52507. * Synchronize and normalize current Animatable with a source Animatable
  52508. * This is useful when using animation weights and when animations are not of the same length
  52509. * @param root defines the root Animatable to synchronize with
  52510. * @returns the current Animatable
  52511. */
  52512. Animatable.prototype.syncWith = function (root) {
  52513. this._syncRoot = root;
  52514. if (root) {
  52515. // Make sure this animatable will animate after the root
  52516. var index = this._scene._activeAnimatables.indexOf(this);
  52517. if (index > -1) {
  52518. this._scene._activeAnimatables.splice(index, 1);
  52519. this._scene._activeAnimatables.push(this);
  52520. }
  52521. }
  52522. return this;
  52523. };
  52524. Animatable.prototype.getAnimations = function () {
  52525. return this._runtimeAnimations;
  52526. };
  52527. Animatable.prototype.appendAnimations = function (target, animations) {
  52528. for (var index = 0; index < animations.length; index++) {
  52529. var animation = animations[index];
  52530. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52531. }
  52532. };
  52533. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52534. var runtimeAnimations = this._runtimeAnimations;
  52535. for (var index = 0; index < runtimeAnimations.length; index++) {
  52536. if (runtimeAnimations[index].animation.targetProperty === property) {
  52537. return runtimeAnimations[index].animation;
  52538. }
  52539. }
  52540. return null;
  52541. };
  52542. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52543. var runtimeAnimations = this._runtimeAnimations;
  52544. for (var index = 0; index < runtimeAnimations.length; index++) {
  52545. if (runtimeAnimations[index].animation.targetProperty === property) {
  52546. return runtimeAnimations[index];
  52547. }
  52548. }
  52549. return null;
  52550. };
  52551. Animatable.prototype.reset = function () {
  52552. var runtimeAnimations = this._runtimeAnimations;
  52553. for (var index = 0; index < runtimeAnimations.length; index++) {
  52554. runtimeAnimations[index].reset(true);
  52555. }
  52556. this._localDelayOffset = null;
  52557. this._pausedDelay = null;
  52558. };
  52559. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52560. var runtimeAnimations = this._runtimeAnimations;
  52561. for (var index = 0; index < runtimeAnimations.length; index++) {
  52562. runtimeAnimations[index].animation.enableBlending = true;
  52563. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52564. }
  52565. };
  52566. Animatable.prototype.disableBlending = function () {
  52567. var runtimeAnimations = this._runtimeAnimations;
  52568. for (var index = 0; index < runtimeAnimations.length; index++) {
  52569. runtimeAnimations[index].animation.enableBlending = false;
  52570. }
  52571. };
  52572. Animatable.prototype.goToFrame = function (frame) {
  52573. var runtimeAnimations = this._runtimeAnimations;
  52574. if (runtimeAnimations[0]) {
  52575. var fps = runtimeAnimations[0].animation.framePerSecond;
  52576. var currentFrame = runtimeAnimations[0].currentFrame;
  52577. var adjustTime = frame - currentFrame;
  52578. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52579. if (this._localDelayOffset === null) {
  52580. this._localDelayOffset = 0;
  52581. }
  52582. this._localDelayOffset -= delay;
  52583. }
  52584. for (var index = 0; index < runtimeAnimations.length; index++) {
  52585. runtimeAnimations[index].goToFrame(frame);
  52586. }
  52587. };
  52588. Animatable.prototype.pause = function () {
  52589. if (this._paused) {
  52590. return;
  52591. }
  52592. this._paused = true;
  52593. };
  52594. Animatable.prototype.restart = function () {
  52595. this._paused = false;
  52596. };
  52597. Animatable.prototype._raiseOnAnimationEnd = function () {
  52598. if (this.onAnimationEnd) {
  52599. this.onAnimationEnd();
  52600. }
  52601. this.onAnimationEndObservable.notifyObservers(this);
  52602. };
  52603. Animatable.prototype.stop = function (animationName) {
  52604. if (animationName) {
  52605. var idx = this._scene._activeAnimatables.indexOf(this);
  52606. if (idx > -1) {
  52607. var runtimeAnimations = this._runtimeAnimations;
  52608. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52609. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52610. continue;
  52611. }
  52612. runtimeAnimations[index].dispose();
  52613. runtimeAnimations.splice(index, 1);
  52614. }
  52615. if (runtimeAnimations.length == 0) {
  52616. this._scene._activeAnimatables.splice(idx, 1);
  52617. this._raiseOnAnimationEnd();
  52618. }
  52619. }
  52620. }
  52621. else {
  52622. var index = this._scene._activeAnimatables.indexOf(this);
  52623. if (index > -1) {
  52624. this._scene._activeAnimatables.splice(index, 1);
  52625. var runtimeAnimations = this._runtimeAnimations;
  52626. for (var index = 0; index < runtimeAnimations.length; index++) {
  52627. runtimeAnimations[index].dispose();
  52628. }
  52629. this._raiseOnAnimationEnd();
  52630. }
  52631. }
  52632. };
  52633. /**
  52634. * Wait asynchronously for the animation to end
  52635. * @returns a promise which will be fullfilled when the animation ends
  52636. */
  52637. Animatable.prototype.waitAsync = function () {
  52638. var _this = this;
  52639. return new Promise(function (resolve, reject) {
  52640. _this.onAnimationEndObservable.add(function () {
  52641. resolve(_this);
  52642. }, undefined, undefined, _this, true);
  52643. });
  52644. };
  52645. /** @hidden */
  52646. Animatable.prototype._animate = function (delay) {
  52647. if (this._paused) {
  52648. this.animationStarted = false;
  52649. if (this._pausedDelay === null) {
  52650. this._pausedDelay = delay;
  52651. }
  52652. return true;
  52653. }
  52654. if (this._localDelayOffset === null) {
  52655. this._localDelayOffset = delay;
  52656. this._pausedDelay = null;
  52657. }
  52658. else if (this._pausedDelay !== null) {
  52659. this._localDelayOffset += delay - this._pausedDelay;
  52660. this._pausedDelay = null;
  52661. }
  52662. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52663. return true;
  52664. }
  52665. // Animating
  52666. var running = false;
  52667. var runtimeAnimations = this._runtimeAnimations;
  52668. var index;
  52669. for (index = 0; index < runtimeAnimations.length; index++) {
  52670. var animation = runtimeAnimations[index];
  52671. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52672. running = running || isRunning;
  52673. }
  52674. this.animationStarted = running;
  52675. if (!running) {
  52676. // Remove from active animatables
  52677. index = this._scene._activeAnimatables.indexOf(this);
  52678. this._scene._activeAnimatables.splice(index, 1);
  52679. // Dispose all runtime animations
  52680. for (index = 0; index < runtimeAnimations.length; index++) {
  52681. runtimeAnimations[index].dispose();
  52682. }
  52683. this._raiseOnAnimationEnd();
  52684. this.onAnimationEnd = null;
  52685. this.onAnimationEndObservable.clear();
  52686. }
  52687. return running;
  52688. };
  52689. return Animatable;
  52690. }());
  52691. BABYLON.Animatable = Animatable;
  52692. })(BABYLON || (BABYLON = {}));
  52693. //# sourceMappingURL=babylon.animatable.js.map
  52694. var BABYLON;
  52695. (function (BABYLON) {
  52696. var EasingFunction = /** @class */ (function () {
  52697. function EasingFunction() {
  52698. // Properties
  52699. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52700. }
  52701. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52702. get: function () {
  52703. return EasingFunction._EASINGMODE_EASEIN;
  52704. },
  52705. enumerable: true,
  52706. configurable: true
  52707. });
  52708. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52709. get: function () {
  52710. return EasingFunction._EASINGMODE_EASEOUT;
  52711. },
  52712. enumerable: true,
  52713. configurable: true
  52714. });
  52715. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52716. get: function () {
  52717. return EasingFunction._EASINGMODE_EASEINOUT;
  52718. },
  52719. enumerable: true,
  52720. configurable: true
  52721. });
  52722. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52723. var n = Math.min(Math.max(easingMode, 0), 2);
  52724. this._easingMode = n;
  52725. };
  52726. EasingFunction.prototype.getEasingMode = function () {
  52727. return this._easingMode;
  52728. };
  52729. EasingFunction.prototype.easeInCore = function (gradient) {
  52730. throw new Error('You must implement this method');
  52731. };
  52732. EasingFunction.prototype.ease = function (gradient) {
  52733. switch (this._easingMode) {
  52734. case EasingFunction.EASINGMODE_EASEIN:
  52735. return this.easeInCore(gradient);
  52736. case EasingFunction.EASINGMODE_EASEOUT:
  52737. return (1 - this.easeInCore(1 - gradient));
  52738. }
  52739. if (gradient >= 0.5) {
  52740. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52741. }
  52742. return (this.easeInCore(gradient * 2) * 0.5);
  52743. };
  52744. //Statics
  52745. EasingFunction._EASINGMODE_EASEIN = 0;
  52746. EasingFunction._EASINGMODE_EASEOUT = 1;
  52747. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52748. return EasingFunction;
  52749. }());
  52750. BABYLON.EasingFunction = EasingFunction;
  52751. var CircleEase = /** @class */ (function (_super) {
  52752. __extends(CircleEase, _super);
  52753. function CircleEase() {
  52754. return _super !== null && _super.apply(this, arguments) || this;
  52755. }
  52756. CircleEase.prototype.easeInCore = function (gradient) {
  52757. gradient = Math.max(0, Math.min(1, gradient));
  52758. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52759. };
  52760. return CircleEase;
  52761. }(EasingFunction));
  52762. BABYLON.CircleEase = CircleEase;
  52763. var BackEase = /** @class */ (function (_super) {
  52764. __extends(BackEase, _super);
  52765. function BackEase(amplitude) {
  52766. if (amplitude === void 0) { amplitude = 1; }
  52767. var _this = _super.call(this) || this;
  52768. _this.amplitude = amplitude;
  52769. return _this;
  52770. }
  52771. BackEase.prototype.easeInCore = function (gradient) {
  52772. var num = Math.max(0, this.amplitude);
  52773. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52774. };
  52775. return BackEase;
  52776. }(EasingFunction));
  52777. BABYLON.BackEase = BackEase;
  52778. var BounceEase = /** @class */ (function (_super) {
  52779. __extends(BounceEase, _super);
  52780. function BounceEase(bounces, bounciness) {
  52781. if (bounces === void 0) { bounces = 3; }
  52782. if (bounciness === void 0) { bounciness = 2; }
  52783. var _this = _super.call(this) || this;
  52784. _this.bounces = bounces;
  52785. _this.bounciness = bounciness;
  52786. return _this;
  52787. }
  52788. BounceEase.prototype.easeInCore = function (gradient) {
  52789. var y = Math.max(0.0, this.bounces);
  52790. var bounciness = this.bounciness;
  52791. if (bounciness <= 1.0) {
  52792. bounciness = 1.001;
  52793. }
  52794. var num9 = Math.pow(bounciness, y);
  52795. var num5 = 1.0 - bounciness;
  52796. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52797. var num15 = gradient * num4;
  52798. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52799. var num3 = Math.floor(num65);
  52800. var num13 = num3 + 1.0;
  52801. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52802. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52803. var num7 = (num8 + num12) * 0.5;
  52804. var num6 = gradient - num7;
  52805. var num2 = num7 - num8;
  52806. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52807. };
  52808. return BounceEase;
  52809. }(EasingFunction));
  52810. BABYLON.BounceEase = BounceEase;
  52811. var CubicEase = /** @class */ (function (_super) {
  52812. __extends(CubicEase, _super);
  52813. function CubicEase() {
  52814. return _super !== null && _super.apply(this, arguments) || this;
  52815. }
  52816. CubicEase.prototype.easeInCore = function (gradient) {
  52817. return (gradient * gradient * gradient);
  52818. };
  52819. return CubicEase;
  52820. }(EasingFunction));
  52821. BABYLON.CubicEase = CubicEase;
  52822. var ElasticEase = /** @class */ (function (_super) {
  52823. __extends(ElasticEase, _super);
  52824. function ElasticEase(oscillations, springiness) {
  52825. if (oscillations === void 0) { oscillations = 3; }
  52826. if (springiness === void 0) { springiness = 3; }
  52827. var _this = _super.call(this) || this;
  52828. _this.oscillations = oscillations;
  52829. _this.springiness = springiness;
  52830. return _this;
  52831. }
  52832. ElasticEase.prototype.easeInCore = function (gradient) {
  52833. var num2;
  52834. var num3 = Math.max(0.0, this.oscillations);
  52835. var num = Math.max(0.0, this.springiness);
  52836. if (num == 0) {
  52837. num2 = gradient;
  52838. }
  52839. else {
  52840. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52841. }
  52842. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52843. };
  52844. return ElasticEase;
  52845. }(EasingFunction));
  52846. BABYLON.ElasticEase = ElasticEase;
  52847. var ExponentialEase = /** @class */ (function (_super) {
  52848. __extends(ExponentialEase, _super);
  52849. function ExponentialEase(exponent) {
  52850. if (exponent === void 0) { exponent = 2; }
  52851. var _this = _super.call(this) || this;
  52852. _this.exponent = exponent;
  52853. return _this;
  52854. }
  52855. ExponentialEase.prototype.easeInCore = function (gradient) {
  52856. if (this.exponent <= 0) {
  52857. return gradient;
  52858. }
  52859. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52860. };
  52861. return ExponentialEase;
  52862. }(EasingFunction));
  52863. BABYLON.ExponentialEase = ExponentialEase;
  52864. var PowerEase = /** @class */ (function (_super) {
  52865. __extends(PowerEase, _super);
  52866. function PowerEase(power) {
  52867. if (power === void 0) { power = 2; }
  52868. var _this = _super.call(this) || this;
  52869. _this.power = power;
  52870. return _this;
  52871. }
  52872. PowerEase.prototype.easeInCore = function (gradient) {
  52873. var y = Math.max(0.0, this.power);
  52874. return Math.pow(gradient, y);
  52875. };
  52876. return PowerEase;
  52877. }(EasingFunction));
  52878. BABYLON.PowerEase = PowerEase;
  52879. var QuadraticEase = /** @class */ (function (_super) {
  52880. __extends(QuadraticEase, _super);
  52881. function QuadraticEase() {
  52882. return _super !== null && _super.apply(this, arguments) || this;
  52883. }
  52884. QuadraticEase.prototype.easeInCore = function (gradient) {
  52885. return (gradient * gradient);
  52886. };
  52887. return QuadraticEase;
  52888. }(EasingFunction));
  52889. BABYLON.QuadraticEase = QuadraticEase;
  52890. var QuarticEase = /** @class */ (function (_super) {
  52891. __extends(QuarticEase, _super);
  52892. function QuarticEase() {
  52893. return _super !== null && _super.apply(this, arguments) || this;
  52894. }
  52895. QuarticEase.prototype.easeInCore = function (gradient) {
  52896. return (gradient * gradient * gradient * gradient);
  52897. };
  52898. return QuarticEase;
  52899. }(EasingFunction));
  52900. BABYLON.QuarticEase = QuarticEase;
  52901. var QuinticEase = /** @class */ (function (_super) {
  52902. __extends(QuinticEase, _super);
  52903. function QuinticEase() {
  52904. return _super !== null && _super.apply(this, arguments) || this;
  52905. }
  52906. QuinticEase.prototype.easeInCore = function (gradient) {
  52907. return (gradient * gradient * gradient * gradient * gradient);
  52908. };
  52909. return QuinticEase;
  52910. }(EasingFunction));
  52911. BABYLON.QuinticEase = QuinticEase;
  52912. var SineEase = /** @class */ (function (_super) {
  52913. __extends(SineEase, _super);
  52914. function SineEase() {
  52915. return _super !== null && _super.apply(this, arguments) || this;
  52916. }
  52917. SineEase.prototype.easeInCore = function (gradient) {
  52918. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52919. };
  52920. return SineEase;
  52921. }(EasingFunction));
  52922. BABYLON.SineEase = SineEase;
  52923. var BezierCurveEase = /** @class */ (function (_super) {
  52924. __extends(BezierCurveEase, _super);
  52925. function BezierCurveEase(x1, y1, x2, y2) {
  52926. if (x1 === void 0) { x1 = 0; }
  52927. if (y1 === void 0) { y1 = 0; }
  52928. if (x2 === void 0) { x2 = 1; }
  52929. if (y2 === void 0) { y2 = 1; }
  52930. var _this = _super.call(this) || this;
  52931. _this.x1 = x1;
  52932. _this.y1 = y1;
  52933. _this.x2 = x2;
  52934. _this.y2 = y2;
  52935. return _this;
  52936. }
  52937. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52938. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52939. };
  52940. return BezierCurveEase;
  52941. }(EasingFunction));
  52942. BABYLON.BezierCurveEase = BezierCurveEase;
  52943. })(BABYLON || (BABYLON = {}));
  52944. //# sourceMappingURL=babylon.easing.js.map
  52945. var BABYLON;
  52946. (function (BABYLON) {
  52947. /**
  52948. * A Condition applied to an Action
  52949. */
  52950. var Condition = /** @class */ (function () {
  52951. /**
  52952. * Creates a new Condition
  52953. * @param actionManager the manager of the action the condition is applied to
  52954. */
  52955. function Condition(actionManager) {
  52956. this._actionManager = actionManager;
  52957. }
  52958. /**
  52959. * Check if the current condition is valid
  52960. * @returns a boolean
  52961. */
  52962. Condition.prototype.isValid = function () {
  52963. return true;
  52964. };
  52965. /**
  52966. * Internal only
  52967. * @hidden
  52968. */
  52969. Condition.prototype._getProperty = function (propertyPath) {
  52970. return this._actionManager._getProperty(propertyPath);
  52971. };
  52972. /**
  52973. * Internal only
  52974. * @hidden
  52975. */
  52976. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52977. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52978. };
  52979. /**
  52980. * Serialize placeholder for child classes
  52981. * @returns the serialized object
  52982. */
  52983. Condition.prototype.serialize = function () {
  52984. };
  52985. /**
  52986. * Internal only
  52987. * @hidden
  52988. */
  52989. Condition.prototype._serialize = function (serializedCondition) {
  52990. return {
  52991. type: 2,
  52992. children: [],
  52993. name: serializedCondition.name,
  52994. properties: serializedCondition.properties
  52995. };
  52996. };
  52997. return Condition;
  52998. }());
  52999. BABYLON.Condition = Condition;
  53000. /**
  53001. * Defines specific conditional operators as extensions of Condition
  53002. */
  53003. var ValueCondition = /** @class */ (function (_super) {
  53004. __extends(ValueCondition, _super);
  53005. /**
  53006. * Creates a new ValueCondition
  53007. * @param actionManager manager for the action the condition applies to
  53008. * @param target for the action
  53009. * @param propertyPath path to specify the property of the target the conditional operator uses
  53010. * @param value the value compared by the conditional operator against the current value of the property
  53011. * @param operator the conditional operator, default ValueCondition.IsEqual
  53012. */
  53013. function ValueCondition(actionManager, target,
  53014. /** path to specify the property of the target the conditional operator uses */
  53015. propertyPath,
  53016. /** the value compared by the conditional operator against the current value of the property */
  53017. value,
  53018. /** the conditional operator, default ValueCondition.IsEqual */
  53019. operator) {
  53020. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53021. var _this = _super.call(this, actionManager) || this;
  53022. _this.propertyPath = propertyPath;
  53023. _this.value = value;
  53024. _this.operator = operator;
  53025. _this._target = target;
  53026. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53027. _this._property = _this._getProperty(_this.propertyPath);
  53028. return _this;
  53029. }
  53030. Object.defineProperty(ValueCondition, "IsEqual", {
  53031. /**
  53032. * returns the number for IsEqual
  53033. */
  53034. get: function () {
  53035. return ValueCondition._IsEqual;
  53036. },
  53037. enumerable: true,
  53038. configurable: true
  53039. });
  53040. Object.defineProperty(ValueCondition, "IsDifferent", {
  53041. /**
  53042. * Returns the number for IsDifferent
  53043. */
  53044. get: function () {
  53045. return ValueCondition._IsDifferent;
  53046. },
  53047. enumerable: true,
  53048. configurable: true
  53049. });
  53050. Object.defineProperty(ValueCondition, "IsGreater", {
  53051. /**
  53052. * Returns the number for IsGreater
  53053. */
  53054. get: function () {
  53055. return ValueCondition._IsGreater;
  53056. },
  53057. enumerable: true,
  53058. configurable: true
  53059. });
  53060. Object.defineProperty(ValueCondition, "IsLesser", {
  53061. /**
  53062. * Returns the number for IsLesser
  53063. */
  53064. get: function () {
  53065. return ValueCondition._IsLesser;
  53066. },
  53067. enumerable: true,
  53068. configurable: true
  53069. });
  53070. /**
  53071. * Compares the given value with the property value for the specified conditional operator
  53072. * @returns the result of the comparison
  53073. */
  53074. ValueCondition.prototype.isValid = function () {
  53075. switch (this.operator) {
  53076. case ValueCondition.IsGreater:
  53077. return this._effectiveTarget[this._property] > this.value;
  53078. case ValueCondition.IsLesser:
  53079. return this._effectiveTarget[this._property] < this.value;
  53080. case ValueCondition.IsEqual:
  53081. case ValueCondition.IsDifferent:
  53082. var check;
  53083. if (this.value.equals) {
  53084. check = this.value.equals(this._effectiveTarget[this._property]);
  53085. }
  53086. else {
  53087. check = this.value === this._effectiveTarget[this._property];
  53088. }
  53089. return this.operator === ValueCondition.IsEqual ? check : !check;
  53090. }
  53091. return false;
  53092. };
  53093. /**
  53094. * Serialize the ValueCondition into a JSON compatible object
  53095. * @returns serialization object
  53096. */
  53097. ValueCondition.prototype.serialize = function () {
  53098. return this._serialize({
  53099. name: "ValueCondition",
  53100. properties: [
  53101. BABYLON.Action._GetTargetProperty(this._target),
  53102. { name: "propertyPath", value: this.propertyPath },
  53103. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53104. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53105. ]
  53106. });
  53107. };
  53108. /**
  53109. * Gets the name of the conditional operator for the ValueCondition
  53110. * @param operator the conditional operator
  53111. * @returns the name
  53112. */
  53113. ValueCondition.GetOperatorName = function (operator) {
  53114. switch (operator) {
  53115. case ValueCondition._IsEqual: return "IsEqual";
  53116. case ValueCondition._IsDifferent: return "IsDifferent";
  53117. case ValueCondition._IsGreater: return "IsGreater";
  53118. case ValueCondition._IsLesser: return "IsLesser";
  53119. default: return "";
  53120. }
  53121. };
  53122. /**
  53123. * Internal only
  53124. * @hidden
  53125. */
  53126. ValueCondition._IsEqual = 0;
  53127. /**
  53128. * Internal only
  53129. * @hidden
  53130. */
  53131. ValueCondition._IsDifferent = 1;
  53132. /**
  53133. * Internal only
  53134. * @hidden
  53135. */
  53136. ValueCondition._IsGreater = 2;
  53137. /**
  53138. * Internal only
  53139. * @hidden
  53140. */
  53141. ValueCondition._IsLesser = 3;
  53142. return ValueCondition;
  53143. }(Condition));
  53144. BABYLON.ValueCondition = ValueCondition;
  53145. /**
  53146. * Defines a predicate condition as an extension of Condition
  53147. */
  53148. var PredicateCondition = /** @class */ (function (_super) {
  53149. __extends(PredicateCondition, _super);
  53150. /**
  53151. * Creates a new PredicateCondition
  53152. * @param actionManager manager for the action the condition applies to
  53153. * @param predicate defines the predicate function used to validate the condition
  53154. */
  53155. function PredicateCondition(actionManager,
  53156. /** defines the predicate function used to validate the condition */
  53157. predicate) {
  53158. var _this = _super.call(this, actionManager) || this;
  53159. _this.predicate = predicate;
  53160. return _this;
  53161. }
  53162. /**
  53163. * @returns the validity of the predicate condition
  53164. */
  53165. PredicateCondition.prototype.isValid = function () {
  53166. return this.predicate();
  53167. };
  53168. return PredicateCondition;
  53169. }(Condition));
  53170. BABYLON.PredicateCondition = PredicateCondition;
  53171. /**
  53172. * Defines a state condition as an extension of Condition
  53173. */
  53174. var StateCondition = /** @class */ (function (_super) {
  53175. __extends(StateCondition, _super);
  53176. /**
  53177. * Creates a new StateCondition
  53178. * @param actionManager manager for the action the condition applies to
  53179. * @param target of the condition
  53180. * @param value to compare with target state
  53181. */
  53182. function StateCondition(actionManager, target, value) {
  53183. var _this = _super.call(this, actionManager) || this;
  53184. _this.value = value;
  53185. _this._target = target;
  53186. return _this;
  53187. }
  53188. /**
  53189. * @returns the validity of the state
  53190. */
  53191. StateCondition.prototype.isValid = function () {
  53192. return this._target.state === this.value;
  53193. };
  53194. /**
  53195. * Serialize the StateCondition into a JSON compatible object
  53196. * @returns serialization object
  53197. */
  53198. StateCondition.prototype.serialize = function () {
  53199. return this._serialize({
  53200. name: "StateCondition",
  53201. properties: [
  53202. BABYLON.Action._GetTargetProperty(this._target),
  53203. { name: "value", value: this.value }
  53204. ]
  53205. });
  53206. };
  53207. return StateCondition;
  53208. }(Condition));
  53209. BABYLON.StateCondition = StateCondition;
  53210. })(BABYLON || (BABYLON = {}));
  53211. //# sourceMappingURL=babylon.condition.js.map
  53212. var BABYLON;
  53213. (function (BABYLON) {
  53214. /**
  53215. * The action to be carried out following a trigger
  53216. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53217. */
  53218. var Action = /** @class */ (function () {
  53219. /**
  53220. * Creates a new Action
  53221. * @param triggerOptions the trigger, with or without parameters, for the action
  53222. * @param condition an optional determinant of action
  53223. */
  53224. function Action(
  53225. /** the trigger, with or without parameters, for the action */
  53226. triggerOptions, condition) {
  53227. this.triggerOptions = triggerOptions;
  53228. /**
  53229. * An event triggered prior to action being executed.
  53230. */
  53231. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53232. if (triggerOptions.parameter) {
  53233. this.trigger = triggerOptions.trigger;
  53234. this._triggerParameter = triggerOptions.parameter;
  53235. }
  53236. else {
  53237. this.trigger = triggerOptions;
  53238. }
  53239. this._nextActiveAction = this;
  53240. this._condition = condition;
  53241. }
  53242. /**
  53243. * Internal only
  53244. * @hidden
  53245. */
  53246. Action.prototype._prepare = function () {
  53247. };
  53248. /**
  53249. * Gets the trigger parameters
  53250. * @returns the trigger parameters
  53251. */
  53252. Action.prototype.getTriggerParameter = function () {
  53253. return this._triggerParameter;
  53254. };
  53255. /**
  53256. * Internal only - executes current action event
  53257. * @hidden
  53258. */
  53259. Action.prototype._executeCurrent = function (evt) {
  53260. if (this._nextActiveAction._condition) {
  53261. var condition = this._nextActiveAction._condition;
  53262. var currentRenderId = this._actionManager.getScene().getRenderId();
  53263. // We cache the current evaluation for the current frame
  53264. if (condition._evaluationId === currentRenderId) {
  53265. if (!condition._currentResult) {
  53266. return;
  53267. }
  53268. }
  53269. else {
  53270. condition._evaluationId = currentRenderId;
  53271. if (!condition.isValid()) {
  53272. condition._currentResult = false;
  53273. return;
  53274. }
  53275. condition._currentResult = true;
  53276. }
  53277. }
  53278. this.onBeforeExecuteObservable.notifyObservers(this);
  53279. this._nextActiveAction.execute(evt);
  53280. this.skipToNextActiveAction();
  53281. };
  53282. /**
  53283. * Execute placeholder for child classes
  53284. * @param evt optional action event
  53285. */
  53286. Action.prototype.execute = function (evt) {
  53287. };
  53288. /**
  53289. * Skips to next active action
  53290. */
  53291. Action.prototype.skipToNextActiveAction = function () {
  53292. if (this._nextActiveAction._child) {
  53293. if (!this._nextActiveAction._child._actionManager) {
  53294. this._nextActiveAction._child._actionManager = this._actionManager;
  53295. }
  53296. this._nextActiveAction = this._nextActiveAction._child;
  53297. }
  53298. else {
  53299. this._nextActiveAction = this;
  53300. }
  53301. };
  53302. /**
  53303. * Adds action to chain of actions, may be a DoNothingAction
  53304. * @param action defines the next action to execute
  53305. * @returns The action passed in
  53306. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53307. */
  53308. Action.prototype.then = function (action) {
  53309. this._child = action;
  53310. action._actionManager = this._actionManager;
  53311. action._prepare();
  53312. return action;
  53313. };
  53314. /**
  53315. * Internal only
  53316. * @hidden
  53317. */
  53318. Action.prototype._getProperty = function (propertyPath) {
  53319. return this._actionManager._getProperty(propertyPath);
  53320. };
  53321. /**
  53322. * Internal only
  53323. * @hidden
  53324. */
  53325. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53326. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53327. };
  53328. /**
  53329. * Serialize placeholder for child classes
  53330. * @param parent of child
  53331. * @returns the serialized object
  53332. */
  53333. Action.prototype.serialize = function (parent) {
  53334. };
  53335. /**
  53336. * Internal only called by serialize
  53337. * @hidden
  53338. */
  53339. Action.prototype._serialize = function (serializedAction, parent) {
  53340. var serializationObject = {
  53341. type: 1,
  53342. children: [],
  53343. name: serializedAction.name,
  53344. properties: serializedAction.properties || []
  53345. };
  53346. // Serialize child
  53347. if (this._child) {
  53348. this._child.serialize(serializationObject);
  53349. }
  53350. // Check if "this" has a condition
  53351. if (this._condition) {
  53352. var serializedCondition = this._condition.serialize();
  53353. serializedCondition.children.push(serializationObject);
  53354. if (parent) {
  53355. parent.children.push(serializedCondition);
  53356. }
  53357. return serializedCondition;
  53358. }
  53359. if (parent) {
  53360. parent.children.push(serializationObject);
  53361. }
  53362. return serializationObject;
  53363. };
  53364. /**
  53365. * Internal only
  53366. * @hidden
  53367. */
  53368. Action._SerializeValueAsString = function (value) {
  53369. if (typeof value === "number") {
  53370. return value.toString();
  53371. }
  53372. if (typeof value === "boolean") {
  53373. return value ? "true" : "false";
  53374. }
  53375. if (value instanceof BABYLON.Vector2) {
  53376. return value.x + ", " + value.y;
  53377. }
  53378. if (value instanceof BABYLON.Vector3) {
  53379. return value.x + ", " + value.y + ", " + value.z;
  53380. }
  53381. if (value instanceof BABYLON.Color3) {
  53382. return value.r + ", " + value.g + ", " + value.b;
  53383. }
  53384. if (value instanceof BABYLON.Color4) {
  53385. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53386. }
  53387. return value; // string
  53388. };
  53389. /**
  53390. * Internal only
  53391. * @hidden
  53392. */
  53393. Action._GetTargetProperty = function (target) {
  53394. return {
  53395. name: "target",
  53396. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53397. : target instanceof BABYLON.Light ? "LightProperties"
  53398. : target instanceof BABYLON.Camera ? "CameraProperties"
  53399. : "SceneProperties",
  53400. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53401. };
  53402. };
  53403. return Action;
  53404. }());
  53405. BABYLON.Action = Action;
  53406. })(BABYLON || (BABYLON = {}));
  53407. //# sourceMappingURL=babylon.action.js.map
  53408. var BABYLON;
  53409. (function (BABYLON) {
  53410. /**
  53411. * ActionEvent is the event being sent when an action is triggered.
  53412. */
  53413. var ActionEvent = /** @class */ (function () {
  53414. /**
  53415. * Creates a new ActionEvent
  53416. * @param source The mesh or sprite that triggered the action
  53417. * @param pointerX The X mouse cursor position at the time of the event
  53418. * @param pointerY The Y mouse cursor position at the time of the event
  53419. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53420. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53421. * @param additionalData additional data for the event
  53422. */
  53423. function ActionEvent(
  53424. /** The mesh or sprite that triggered the action */
  53425. source,
  53426. /** The X mouse cursor position at the time of the event */
  53427. pointerX,
  53428. /** The Y mouse cursor position at the time of the event */
  53429. pointerY,
  53430. /** The mesh that is currently pointed at (can be null) */
  53431. meshUnderPointer,
  53432. /** the original (browser) event that triggered the ActionEvent */
  53433. sourceEvent,
  53434. /** additional data for the event */
  53435. additionalData) {
  53436. this.source = source;
  53437. this.pointerX = pointerX;
  53438. this.pointerY = pointerY;
  53439. this.meshUnderPointer = meshUnderPointer;
  53440. this.sourceEvent = sourceEvent;
  53441. this.additionalData = additionalData;
  53442. }
  53443. /**
  53444. * Helper function to auto-create an ActionEvent from a source mesh.
  53445. * @param source The source mesh that triggered the event
  53446. * @param evt The original (browser) event
  53447. * @param additionalData additional data for the event
  53448. * @returns the new ActionEvent
  53449. */
  53450. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53451. var scene = source.getScene();
  53452. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53453. };
  53454. /**
  53455. * Helper function to auto-create an ActionEvent from a source sprite
  53456. * @param source The source sprite that triggered the event
  53457. * @param scene Scene associated with the sprite
  53458. * @param evt The original (browser) event
  53459. * @param additionalData additional data for the event
  53460. * @returns the new ActionEvent
  53461. */
  53462. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53463. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53464. };
  53465. /**
  53466. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53467. * @param scene the scene where the event occurred
  53468. * @param evt The original (browser) event
  53469. * @returns the new ActionEvent
  53470. */
  53471. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53472. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53473. };
  53474. /**
  53475. * Helper function to auto-create an ActionEvent from a primitive
  53476. * @param prim defines the target primitive
  53477. * @param pointerPos defines the pointer position
  53478. * @param evt The original (browser) event
  53479. * @param additionalData additional data for the event
  53480. * @returns the new ActionEvent
  53481. */
  53482. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53483. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53484. };
  53485. return ActionEvent;
  53486. }());
  53487. BABYLON.ActionEvent = ActionEvent;
  53488. /**
  53489. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53490. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53491. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53492. */
  53493. var ActionManager = /** @class */ (function () {
  53494. /**
  53495. * Creates a new action manager
  53496. * @param scene defines the hosting scene
  53497. */
  53498. function ActionManager(scene) {
  53499. // Members
  53500. /** Gets the list of actions */
  53501. this.actions = new Array();
  53502. /** Gets the cursor to use when hovering items */
  53503. this.hoverCursor = '';
  53504. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53505. scene._actionManagers.push(this);
  53506. }
  53507. Object.defineProperty(ActionManager, "NothingTrigger", {
  53508. /**
  53509. * Nothing
  53510. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53511. */
  53512. get: function () {
  53513. return ActionManager._NothingTrigger;
  53514. },
  53515. enumerable: true,
  53516. configurable: true
  53517. });
  53518. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53519. /**
  53520. * On pick
  53521. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53522. */
  53523. get: function () {
  53524. return ActionManager._OnPickTrigger;
  53525. },
  53526. enumerable: true,
  53527. configurable: true
  53528. });
  53529. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53530. /**
  53531. * On left pick
  53532. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53533. */
  53534. get: function () {
  53535. return ActionManager._OnLeftPickTrigger;
  53536. },
  53537. enumerable: true,
  53538. configurable: true
  53539. });
  53540. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53541. /**
  53542. * On right pick
  53543. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53544. */
  53545. get: function () {
  53546. return ActionManager._OnRightPickTrigger;
  53547. },
  53548. enumerable: true,
  53549. configurable: true
  53550. });
  53551. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53552. /**
  53553. * On center pick
  53554. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53555. */
  53556. get: function () {
  53557. return ActionManager._OnCenterPickTrigger;
  53558. },
  53559. enumerable: true,
  53560. configurable: true
  53561. });
  53562. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53563. /**
  53564. * On pick down
  53565. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53566. */
  53567. get: function () {
  53568. return ActionManager._OnPickDownTrigger;
  53569. },
  53570. enumerable: true,
  53571. configurable: true
  53572. });
  53573. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53574. /**
  53575. * On double pick
  53576. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53577. */
  53578. get: function () {
  53579. return ActionManager._OnDoublePickTrigger;
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53585. /**
  53586. * On pick up
  53587. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53588. */
  53589. get: function () {
  53590. return ActionManager._OnPickUpTrigger;
  53591. },
  53592. enumerable: true,
  53593. configurable: true
  53594. });
  53595. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53596. /**
  53597. * On pick out.
  53598. * This trigger will only be raised if you also declared a OnPickDown
  53599. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53600. */
  53601. get: function () {
  53602. return ActionManager._OnPickOutTrigger;
  53603. },
  53604. enumerable: true,
  53605. configurable: true
  53606. });
  53607. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53608. /**
  53609. * On long press
  53610. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53611. */
  53612. get: function () {
  53613. return ActionManager._OnLongPressTrigger;
  53614. },
  53615. enumerable: true,
  53616. configurable: true
  53617. });
  53618. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53619. /**
  53620. * On pointer over
  53621. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53622. */
  53623. get: function () {
  53624. return ActionManager._OnPointerOverTrigger;
  53625. },
  53626. enumerable: true,
  53627. configurable: true
  53628. });
  53629. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53630. /**
  53631. * On pointer out
  53632. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53633. */
  53634. get: function () {
  53635. return ActionManager._OnPointerOutTrigger;
  53636. },
  53637. enumerable: true,
  53638. configurable: true
  53639. });
  53640. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53641. /**
  53642. * On every frame
  53643. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53644. */
  53645. get: function () {
  53646. return ActionManager._OnEveryFrameTrigger;
  53647. },
  53648. enumerable: true,
  53649. configurable: true
  53650. });
  53651. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53652. /**
  53653. * On intersection enter
  53654. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53655. */
  53656. get: function () {
  53657. return ActionManager._OnIntersectionEnterTrigger;
  53658. },
  53659. enumerable: true,
  53660. configurable: true
  53661. });
  53662. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53663. /**
  53664. * On intersection exit
  53665. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53666. */
  53667. get: function () {
  53668. return ActionManager._OnIntersectionExitTrigger;
  53669. },
  53670. enumerable: true,
  53671. configurable: true
  53672. });
  53673. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53674. /**
  53675. * On key down
  53676. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53677. */
  53678. get: function () {
  53679. return ActionManager._OnKeyDownTrigger;
  53680. },
  53681. enumerable: true,
  53682. configurable: true
  53683. });
  53684. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53685. /**
  53686. * On key up
  53687. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53688. */
  53689. get: function () {
  53690. return ActionManager._OnKeyUpTrigger;
  53691. },
  53692. enumerable: true,
  53693. configurable: true
  53694. });
  53695. // Methods
  53696. /**
  53697. * Releases all associated resources
  53698. */
  53699. ActionManager.prototype.dispose = function () {
  53700. var index = this._scene._actionManagers.indexOf(this);
  53701. for (var i = 0; i < this.actions.length; i++) {
  53702. var action = this.actions[i];
  53703. ActionManager.Triggers[action.trigger]--;
  53704. if (ActionManager.Triggers[action.trigger] === 0) {
  53705. delete ActionManager.Triggers[action.trigger];
  53706. }
  53707. }
  53708. if (index > -1) {
  53709. this._scene._actionManagers.splice(index, 1);
  53710. }
  53711. };
  53712. /**
  53713. * Gets hosting scene
  53714. * @returns the hosting scene
  53715. */
  53716. ActionManager.prototype.getScene = function () {
  53717. return this._scene;
  53718. };
  53719. /**
  53720. * Does this action manager handles actions of any of the given triggers
  53721. * @param triggers defines the triggers to be tested
  53722. * @return a boolean indicating whether one (or more) of the triggers is handled
  53723. */
  53724. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53725. for (var index = 0; index < this.actions.length; index++) {
  53726. var action = this.actions[index];
  53727. if (triggers.indexOf(action.trigger) > -1) {
  53728. return true;
  53729. }
  53730. }
  53731. return false;
  53732. };
  53733. /**
  53734. * Does this action manager handles actions of a given trigger
  53735. * @param trigger defines the trigger to be tested
  53736. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53737. * @return whether the trigger is handled
  53738. */
  53739. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53740. for (var index = 0; index < this.actions.length; index++) {
  53741. var action = this.actions[index];
  53742. if (action.trigger === trigger) {
  53743. if (parameterPredicate) {
  53744. if (parameterPredicate(action.getTriggerParameter())) {
  53745. return true;
  53746. }
  53747. }
  53748. else {
  53749. return true;
  53750. }
  53751. }
  53752. }
  53753. return false;
  53754. };
  53755. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53756. /**
  53757. * Does this action manager has pointer triggers
  53758. */
  53759. get: function () {
  53760. for (var index = 0; index < this.actions.length; index++) {
  53761. var action = this.actions[index];
  53762. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53763. return true;
  53764. }
  53765. }
  53766. return false;
  53767. },
  53768. enumerable: true,
  53769. configurable: true
  53770. });
  53771. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53772. /**
  53773. * Does this action manager has pick triggers
  53774. */
  53775. get: function () {
  53776. for (var index = 0; index < this.actions.length; index++) {
  53777. var action = this.actions[index];
  53778. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53779. return true;
  53780. }
  53781. }
  53782. return false;
  53783. },
  53784. enumerable: true,
  53785. configurable: true
  53786. });
  53787. Object.defineProperty(ActionManager, "HasTriggers", {
  53788. /**
  53789. * Does exist one action manager with at least one trigger
  53790. **/
  53791. get: function () {
  53792. for (var t in ActionManager.Triggers) {
  53793. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53794. return true;
  53795. }
  53796. }
  53797. return false;
  53798. },
  53799. enumerable: true,
  53800. configurable: true
  53801. });
  53802. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53803. /**
  53804. * Does exist one action manager with at least one pick trigger
  53805. **/
  53806. get: function () {
  53807. for (var t in ActionManager.Triggers) {
  53808. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53809. var t_int = parseInt(t);
  53810. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53811. return true;
  53812. }
  53813. }
  53814. }
  53815. return false;
  53816. },
  53817. enumerable: true,
  53818. configurable: true
  53819. });
  53820. /**
  53821. * Does exist one action manager that handles actions of a given trigger
  53822. * @param trigger defines the trigger to be tested
  53823. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53824. **/
  53825. ActionManager.HasSpecificTrigger = function (trigger) {
  53826. for (var t in ActionManager.Triggers) {
  53827. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53828. var t_int = parseInt(t);
  53829. if (t_int === trigger) {
  53830. return true;
  53831. }
  53832. }
  53833. }
  53834. return false;
  53835. };
  53836. /**
  53837. * Registers an action to this action manager
  53838. * @param action defines the action to be registered
  53839. * @return the action amended (prepared) after registration
  53840. */
  53841. ActionManager.prototype.registerAction = function (action) {
  53842. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53843. if (this.getScene().actionManager !== this) {
  53844. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53845. return null;
  53846. }
  53847. }
  53848. this.actions.push(action);
  53849. if (ActionManager.Triggers[action.trigger]) {
  53850. ActionManager.Triggers[action.trigger]++;
  53851. }
  53852. else {
  53853. ActionManager.Triggers[action.trigger] = 1;
  53854. }
  53855. action._actionManager = this;
  53856. action._prepare();
  53857. return action;
  53858. };
  53859. /**
  53860. * Unregisters an action to this action manager
  53861. * @param action defines the action to be unregistered
  53862. * @return a boolean indicating whether the action has been unregistered
  53863. */
  53864. ActionManager.prototype.unregisterAction = function (action) {
  53865. var index = this.actions.indexOf(action);
  53866. if (index !== -1) {
  53867. this.actions.splice(index, 1);
  53868. ActionManager.Triggers[action.trigger] -= 1;
  53869. if (ActionManager.Triggers[action.trigger] === 0) {
  53870. delete ActionManager.Triggers[action.trigger];
  53871. }
  53872. delete action._actionManager;
  53873. return true;
  53874. }
  53875. return false;
  53876. };
  53877. /**
  53878. * Process a specific trigger
  53879. * @param trigger defines the trigger to process
  53880. * @param evt defines the event details to be processed
  53881. */
  53882. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53883. for (var index = 0; index < this.actions.length; index++) {
  53884. var action = this.actions[index];
  53885. if (action.trigger === trigger) {
  53886. if (evt) {
  53887. if (trigger === ActionManager.OnKeyUpTrigger
  53888. || trigger === ActionManager.OnKeyDownTrigger) {
  53889. var parameter = action.getTriggerParameter();
  53890. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53891. if (!parameter.toLowerCase) {
  53892. continue;
  53893. }
  53894. var lowerCase = parameter.toLowerCase();
  53895. if (lowerCase !== evt.sourceEvent.key) {
  53896. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53897. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53898. if (actualkey !== lowerCase) {
  53899. continue;
  53900. }
  53901. }
  53902. }
  53903. }
  53904. }
  53905. action._executeCurrent(evt);
  53906. }
  53907. }
  53908. };
  53909. /** @hidden */
  53910. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53911. var properties = propertyPath.split(".");
  53912. for (var index = 0; index < properties.length - 1; index++) {
  53913. target = target[properties[index]];
  53914. }
  53915. return target;
  53916. };
  53917. /** @hidden */
  53918. ActionManager.prototype._getProperty = function (propertyPath) {
  53919. var properties = propertyPath.split(".");
  53920. return properties[properties.length - 1];
  53921. };
  53922. /**
  53923. * Serialize this manager to a JSON object
  53924. * @param name defines the property name to store this manager
  53925. * @returns a JSON representation of this manager
  53926. */
  53927. ActionManager.prototype.serialize = function (name) {
  53928. var root = {
  53929. children: new Array(),
  53930. name: name,
  53931. type: 3,
  53932. properties: new Array() // Empty for root but required
  53933. };
  53934. for (var i = 0; i < this.actions.length; i++) {
  53935. var triggerObject = {
  53936. type: 0,
  53937. children: new Array(),
  53938. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53939. properties: new Array()
  53940. };
  53941. var triggerOptions = this.actions[i].triggerOptions;
  53942. if (triggerOptions && typeof triggerOptions !== "number") {
  53943. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53944. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53945. }
  53946. else {
  53947. var parameter = {};
  53948. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53949. if (triggerOptions.parameter.mesh) {
  53950. parameter._meshId = triggerOptions.parameter.mesh.id;
  53951. }
  53952. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53953. }
  53954. }
  53955. // Serialize child action, recursively
  53956. this.actions[i].serialize(triggerObject);
  53957. // Add serialized trigger
  53958. root.children.push(triggerObject);
  53959. }
  53960. return root;
  53961. };
  53962. /**
  53963. * Creates a new ActionManager from a JSON data
  53964. * @param parsedActions defines the JSON data to read from
  53965. * @param object defines the hosting mesh
  53966. * @param scene defines the hosting scene
  53967. */
  53968. ActionManager.Parse = function (parsedActions, object, scene) {
  53969. var actionManager = new ActionManager(scene);
  53970. if (object === null)
  53971. scene.actionManager = actionManager;
  53972. else
  53973. object.actionManager = actionManager;
  53974. // instanciate a new object
  53975. var instanciate = function (name, params) {
  53976. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53977. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53978. newInstance.constructor.apply(newInstance, params);
  53979. return newInstance;
  53980. };
  53981. var parseParameter = function (name, value, target, propertyPath) {
  53982. if (propertyPath === null) {
  53983. // String, boolean or float
  53984. var floatValue = parseFloat(value);
  53985. if (value === "true" || value === "false")
  53986. return value === "true";
  53987. else
  53988. return isNaN(floatValue) ? value : floatValue;
  53989. }
  53990. var effectiveTarget = propertyPath.split(".");
  53991. var values = value.split(",");
  53992. // Get effective Target
  53993. for (var i = 0; i < effectiveTarget.length; i++) {
  53994. target = target[effectiveTarget[i]];
  53995. }
  53996. // Return appropriate value with its type
  53997. if (typeof (target) === "boolean")
  53998. return values[0] === "true";
  53999. if (typeof (target) === "string")
  54000. return values[0];
  54001. // Parameters with multiple values such as Vector3 etc.
  54002. var split = new Array();
  54003. for (var i = 0; i < values.length; i++)
  54004. split.push(parseFloat(values[i]));
  54005. if (target instanceof BABYLON.Vector3)
  54006. return BABYLON.Vector3.FromArray(split);
  54007. if (target instanceof BABYLON.Vector4)
  54008. return BABYLON.Vector4.FromArray(split);
  54009. if (target instanceof BABYLON.Color3)
  54010. return BABYLON.Color3.FromArray(split);
  54011. if (target instanceof BABYLON.Color4)
  54012. return BABYLON.Color4.FromArray(split);
  54013. return parseFloat(values[0]);
  54014. };
  54015. // traverse graph per trigger
  54016. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54017. if (combineArray === void 0) { combineArray = null; }
  54018. if (parsedAction.detached)
  54019. return;
  54020. var parameters = new Array();
  54021. var target = null;
  54022. var propertyPath = null;
  54023. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54024. // Parameters
  54025. if (parsedAction.type === 2)
  54026. parameters.push(actionManager);
  54027. else
  54028. parameters.push(trigger);
  54029. if (combine) {
  54030. var actions = new Array();
  54031. for (var j = 0; j < parsedAction.combine.length; j++) {
  54032. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54033. }
  54034. parameters.push(actions);
  54035. }
  54036. else {
  54037. for (var i = 0; i < parsedAction.properties.length; i++) {
  54038. var value = parsedAction.properties[i].value;
  54039. var name = parsedAction.properties[i].name;
  54040. var targetType = parsedAction.properties[i].targetType;
  54041. if (name === "target")
  54042. if (targetType !== null && targetType === "SceneProperties")
  54043. value = target = scene;
  54044. else
  54045. value = target = scene.getNodeByName(value);
  54046. else if (name === "parent")
  54047. value = scene.getNodeByName(value);
  54048. else if (name === "sound")
  54049. value = scene.getSoundByName(value);
  54050. else if (name !== "propertyPath") {
  54051. if (parsedAction.type === 2 && name === "operator")
  54052. value = BABYLON.ValueCondition[value];
  54053. else
  54054. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54055. }
  54056. else {
  54057. propertyPath = value;
  54058. }
  54059. parameters.push(value);
  54060. }
  54061. }
  54062. if (combineArray === null) {
  54063. parameters.push(condition);
  54064. }
  54065. else {
  54066. parameters.push(null);
  54067. }
  54068. // If interpolate value action
  54069. if (parsedAction.name === "InterpolateValueAction") {
  54070. var param = parameters[parameters.length - 2];
  54071. parameters[parameters.length - 1] = param;
  54072. parameters[parameters.length - 2] = condition;
  54073. }
  54074. // Action or condition(s) and not CombineAction
  54075. var newAction = instanciate(parsedAction.name, parameters);
  54076. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54077. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54078. if (action)
  54079. action.then(nothing);
  54080. else
  54081. actionManager.registerAction(nothing);
  54082. action = nothing;
  54083. }
  54084. if (combineArray === null) {
  54085. if (newAction instanceof BABYLON.Condition) {
  54086. condition = newAction;
  54087. newAction = action;
  54088. }
  54089. else {
  54090. condition = null;
  54091. if (action)
  54092. action.then(newAction);
  54093. else
  54094. actionManager.registerAction(newAction);
  54095. }
  54096. }
  54097. else {
  54098. combineArray.push(newAction);
  54099. }
  54100. for (var i = 0; i < parsedAction.children.length; i++)
  54101. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54102. };
  54103. // triggers
  54104. for (var i = 0; i < parsedActions.children.length; i++) {
  54105. var triggerParams;
  54106. var trigger = parsedActions.children[i];
  54107. if (trigger.properties.length > 0) {
  54108. var param = trigger.properties[0].value;
  54109. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54110. if (value._meshId) {
  54111. value.mesh = scene.getMeshByID(value._meshId);
  54112. }
  54113. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54114. }
  54115. else
  54116. triggerParams = ActionManager[trigger.name];
  54117. for (var j = 0; j < trigger.children.length; j++) {
  54118. if (!trigger.detached)
  54119. traverse(trigger.children[j], triggerParams, null, null);
  54120. }
  54121. }
  54122. };
  54123. /**
  54124. * Get a trigger name by index
  54125. * @param trigger defines the trigger index
  54126. * @returns a trigger name
  54127. */
  54128. ActionManager.GetTriggerName = function (trigger) {
  54129. switch (trigger) {
  54130. case 0: return "NothingTrigger";
  54131. case 1: return "OnPickTrigger";
  54132. case 2: return "OnLeftPickTrigger";
  54133. case 3: return "OnRightPickTrigger";
  54134. case 4: return "OnCenterPickTrigger";
  54135. case 5: return "OnPickDownTrigger";
  54136. case 6: return "OnPickUpTrigger";
  54137. case 7: return "OnLongPressTrigger";
  54138. case 8: return "OnPointerOverTrigger";
  54139. case 9: return "OnPointerOutTrigger";
  54140. case 10: return "OnEveryFrameTrigger";
  54141. case 11: return "OnIntersectionEnterTrigger";
  54142. case 12: return "OnIntersectionExitTrigger";
  54143. case 13: return "OnKeyDownTrigger";
  54144. case 14: return "OnKeyUpTrigger";
  54145. case 15: return "OnPickOutTrigger";
  54146. default: return "";
  54147. }
  54148. };
  54149. // Statics
  54150. ActionManager._NothingTrigger = 0;
  54151. ActionManager._OnPickTrigger = 1;
  54152. ActionManager._OnLeftPickTrigger = 2;
  54153. ActionManager._OnRightPickTrigger = 3;
  54154. ActionManager._OnCenterPickTrigger = 4;
  54155. ActionManager._OnPickDownTrigger = 5;
  54156. ActionManager._OnDoublePickTrigger = 6;
  54157. ActionManager._OnPickUpTrigger = 7;
  54158. ActionManager._OnLongPressTrigger = 8;
  54159. ActionManager._OnPointerOverTrigger = 9;
  54160. ActionManager._OnPointerOutTrigger = 10;
  54161. ActionManager._OnEveryFrameTrigger = 11;
  54162. ActionManager._OnIntersectionEnterTrigger = 12;
  54163. ActionManager._OnIntersectionExitTrigger = 13;
  54164. ActionManager._OnKeyDownTrigger = 14;
  54165. ActionManager._OnKeyUpTrigger = 15;
  54166. ActionManager._OnPickOutTrigger = 16;
  54167. /** Gets the list of active triggers */
  54168. ActionManager.Triggers = {};
  54169. return ActionManager;
  54170. }());
  54171. BABYLON.ActionManager = ActionManager;
  54172. })(BABYLON || (BABYLON = {}));
  54173. //# sourceMappingURL=babylon.actionManager.js.map
  54174. var BABYLON;
  54175. (function (BABYLON) {
  54176. var InterpolateValueAction = /** @class */ (function (_super) {
  54177. __extends(InterpolateValueAction, _super);
  54178. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54179. if (duration === void 0) { duration = 1000; }
  54180. var _this = _super.call(this, triggerOptions, condition) || this;
  54181. _this.propertyPath = propertyPath;
  54182. _this.value = value;
  54183. _this.duration = duration;
  54184. _this.stopOtherAnimations = stopOtherAnimations;
  54185. _this.onInterpolationDone = onInterpolationDone;
  54186. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54187. _this._target = _this._effectiveTarget = target;
  54188. return _this;
  54189. }
  54190. InterpolateValueAction.prototype._prepare = function () {
  54191. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54192. this._property = this._getProperty(this.propertyPath);
  54193. };
  54194. InterpolateValueAction.prototype.execute = function () {
  54195. var _this = this;
  54196. var scene = this._actionManager.getScene();
  54197. var keys = [
  54198. {
  54199. frame: 0,
  54200. value: this._effectiveTarget[this._property]
  54201. }, {
  54202. frame: 100,
  54203. value: this.value
  54204. }
  54205. ];
  54206. var dataType;
  54207. if (typeof this.value === "number") {
  54208. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54209. }
  54210. else if (this.value instanceof BABYLON.Color3) {
  54211. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54212. }
  54213. else if (this.value instanceof BABYLON.Vector3) {
  54214. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54215. }
  54216. else if (this.value instanceof BABYLON.Matrix) {
  54217. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54218. }
  54219. else if (this.value instanceof BABYLON.Quaternion) {
  54220. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54221. }
  54222. else {
  54223. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54224. return;
  54225. }
  54226. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54227. animation.setKeys(keys);
  54228. if (this.stopOtherAnimations) {
  54229. scene.stopAnimation(this._effectiveTarget);
  54230. }
  54231. var wrapper = function () {
  54232. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54233. if (_this.onInterpolationDone) {
  54234. _this.onInterpolationDone();
  54235. }
  54236. };
  54237. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54238. };
  54239. InterpolateValueAction.prototype.serialize = function (parent) {
  54240. return _super.prototype._serialize.call(this, {
  54241. name: "InterpolateValueAction",
  54242. properties: [
  54243. BABYLON.Action._GetTargetProperty(this._target),
  54244. { name: "propertyPath", value: this.propertyPath },
  54245. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54246. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54247. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54248. ]
  54249. }, parent);
  54250. };
  54251. return InterpolateValueAction;
  54252. }(BABYLON.Action));
  54253. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54254. })(BABYLON || (BABYLON = {}));
  54255. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54256. var BABYLON;
  54257. (function (BABYLON) {
  54258. var SwitchBooleanAction = /** @class */ (function (_super) {
  54259. __extends(SwitchBooleanAction, _super);
  54260. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54261. var _this = _super.call(this, triggerOptions, condition) || this;
  54262. _this.propertyPath = propertyPath;
  54263. _this._target = _this._effectiveTarget = target;
  54264. return _this;
  54265. }
  54266. SwitchBooleanAction.prototype._prepare = function () {
  54267. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54268. this._property = this._getProperty(this.propertyPath);
  54269. };
  54270. SwitchBooleanAction.prototype.execute = function () {
  54271. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54272. };
  54273. SwitchBooleanAction.prototype.serialize = function (parent) {
  54274. return _super.prototype._serialize.call(this, {
  54275. name: "SwitchBooleanAction",
  54276. properties: [
  54277. BABYLON.Action._GetTargetProperty(this._target),
  54278. { name: "propertyPath", value: this.propertyPath }
  54279. ]
  54280. }, parent);
  54281. };
  54282. return SwitchBooleanAction;
  54283. }(BABYLON.Action));
  54284. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54285. var SetStateAction = /** @class */ (function (_super) {
  54286. __extends(SetStateAction, _super);
  54287. function SetStateAction(triggerOptions, target, value, condition) {
  54288. var _this = _super.call(this, triggerOptions, condition) || this;
  54289. _this.value = value;
  54290. _this._target = target;
  54291. return _this;
  54292. }
  54293. SetStateAction.prototype.execute = function () {
  54294. this._target.state = this.value;
  54295. };
  54296. SetStateAction.prototype.serialize = function (parent) {
  54297. return _super.prototype._serialize.call(this, {
  54298. name: "SetStateAction",
  54299. properties: [
  54300. BABYLON.Action._GetTargetProperty(this._target),
  54301. { name: "value", value: this.value }
  54302. ]
  54303. }, parent);
  54304. };
  54305. return SetStateAction;
  54306. }(BABYLON.Action));
  54307. BABYLON.SetStateAction = SetStateAction;
  54308. var SetValueAction = /** @class */ (function (_super) {
  54309. __extends(SetValueAction, _super);
  54310. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54311. var _this = _super.call(this, triggerOptions, condition) || this;
  54312. _this.propertyPath = propertyPath;
  54313. _this.value = value;
  54314. _this._target = _this._effectiveTarget = target;
  54315. return _this;
  54316. }
  54317. SetValueAction.prototype._prepare = function () {
  54318. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54319. this._property = this._getProperty(this.propertyPath);
  54320. };
  54321. SetValueAction.prototype.execute = function () {
  54322. this._effectiveTarget[this._property] = this.value;
  54323. if (this._target.markAsDirty) {
  54324. this._target.markAsDirty(this._property);
  54325. }
  54326. };
  54327. SetValueAction.prototype.serialize = function (parent) {
  54328. return _super.prototype._serialize.call(this, {
  54329. name: "SetValueAction",
  54330. properties: [
  54331. BABYLON.Action._GetTargetProperty(this._target),
  54332. { name: "propertyPath", value: this.propertyPath },
  54333. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54334. ]
  54335. }, parent);
  54336. };
  54337. return SetValueAction;
  54338. }(BABYLON.Action));
  54339. BABYLON.SetValueAction = SetValueAction;
  54340. var IncrementValueAction = /** @class */ (function (_super) {
  54341. __extends(IncrementValueAction, _super);
  54342. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54343. var _this = _super.call(this, triggerOptions, condition) || this;
  54344. _this.propertyPath = propertyPath;
  54345. _this.value = value;
  54346. _this._target = _this._effectiveTarget = target;
  54347. return _this;
  54348. }
  54349. IncrementValueAction.prototype._prepare = function () {
  54350. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54351. this._property = this._getProperty(this.propertyPath);
  54352. if (typeof this._effectiveTarget[this._property] !== "number") {
  54353. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54354. }
  54355. };
  54356. IncrementValueAction.prototype.execute = function () {
  54357. this._effectiveTarget[this._property] += this.value;
  54358. if (this._target.markAsDirty) {
  54359. this._target.markAsDirty(this._property);
  54360. }
  54361. };
  54362. IncrementValueAction.prototype.serialize = function (parent) {
  54363. return _super.prototype._serialize.call(this, {
  54364. name: "IncrementValueAction",
  54365. properties: [
  54366. BABYLON.Action._GetTargetProperty(this._target),
  54367. { name: "propertyPath", value: this.propertyPath },
  54368. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54369. ]
  54370. }, parent);
  54371. };
  54372. return IncrementValueAction;
  54373. }(BABYLON.Action));
  54374. BABYLON.IncrementValueAction = IncrementValueAction;
  54375. var PlayAnimationAction = /** @class */ (function (_super) {
  54376. __extends(PlayAnimationAction, _super);
  54377. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54378. var _this = _super.call(this, triggerOptions, condition) || this;
  54379. _this.from = from;
  54380. _this.to = to;
  54381. _this.loop = loop;
  54382. _this._target = target;
  54383. return _this;
  54384. }
  54385. PlayAnimationAction.prototype._prepare = function () {
  54386. };
  54387. PlayAnimationAction.prototype.execute = function () {
  54388. var scene = this._actionManager.getScene();
  54389. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54390. };
  54391. PlayAnimationAction.prototype.serialize = function (parent) {
  54392. return _super.prototype._serialize.call(this, {
  54393. name: "PlayAnimationAction",
  54394. properties: [
  54395. BABYLON.Action._GetTargetProperty(this._target),
  54396. { name: "from", value: String(this.from) },
  54397. { name: "to", value: String(this.to) },
  54398. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54399. ]
  54400. }, parent);
  54401. };
  54402. return PlayAnimationAction;
  54403. }(BABYLON.Action));
  54404. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54405. var StopAnimationAction = /** @class */ (function (_super) {
  54406. __extends(StopAnimationAction, _super);
  54407. function StopAnimationAction(triggerOptions, target, condition) {
  54408. var _this = _super.call(this, triggerOptions, condition) || this;
  54409. _this._target = target;
  54410. return _this;
  54411. }
  54412. StopAnimationAction.prototype._prepare = function () {
  54413. };
  54414. StopAnimationAction.prototype.execute = function () {
  54415. var scene = this._actionManager.getScene();
  54416. scene.stopAnimation(this._target);
  54417. };
  54418. StopAnimationAction.prototype.serialize = function (parent) {
  54419. return _super.prototype._serialize.call(this, {
  54420. name: "StopAnimationAction",
  54421. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54422. }, parent);
  54423. };
  54424. return StopAnimationAction;
  54425. }(BABYLON.Action));
  54426. BABYLON.StopAnimationAction = StopAnimationAction;
  54427. var DoNothingAction = /** @class */ (function (_super) {
  54428. __extends(DoNothingAction, _super);
  54429. function DoNothingAction(triggerOptions, condition) {
  54430. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54431. return _super.call(this, triggerOptions, condition) || this;
  54432. }
  54433. DoNothingAction.prototype.execute = function () {
  54434. };
  54435. DoNothingAction.prototype.serialize = function (parent) {
  54436. return _super.prototype._serialize.call(this, {
  54437. name: "DoNothingAction",
  54438. properties: []
  54439. }, parent);
  54440. };
  54441. return DoNothingAction;
  54442. }(BABYLON.Action));
  54443. BABYLON.DoNothingAction = DoNothingAction;
  54444. var CombineAction = /** @class */ (function (_super) {
  54445. __extends(CombineAction, _super);
  54446. function CombineAction(triggerOptions, children, condition) {
  54447. var _this = _super.call(this, triggerOptions, condition) || this;
  54448. _this.children = children;
  54449. return _this;
  54450. }
  54451. CombineAction.prototype._prepare = function () {
  54452. for (var index = 0; index < this.children.length; index++) {
  54453. this.children[index]._actionManager = this._actionManager;
  54454. this.children[index]._prepare();
  54455. }
  54456. };
  54457. CombineAction.prototype.execute = function (evt) {
  54458. for (var index = 0; index < this.children.length; index++) {
  54459. this.children[index].execute(evt);
  54460. }
  54461. };
  54462. CombineAction.prototype.serialize = function (parent) {
  54463. var serializationObject = _super.prototype._serialize.call(this, {
  54464. name: "CombineAction",
  54465. properties: [],
  54466. combine: []
  54467. }, parent);
  54468. for (var i = 0; i < this.children.length; i++) {
  54469. serializationObject.combine.push(this.children[i].serialize(null));
  54470. }
  54471. return serializationObject;
  54472. };
  54473. return CombineAction;
  54474. }(BABYLON.Action));
  54475. BABYLON.CombineAction = CombineAction;
  54476. var ExecuteCodeAction = /** @class */ (function (_super) {
  54477. __extends(ExecuteCodeAction, _super);
  54478. function ExecuteCodeAction(triggerOptions, func, condition) {
  54479. var _this = _super.call(this, triggerOptions, condition) || this;
  54480. _this.func = func;
  54481. return _this;
  54482. }
  54483. ExecuteCodeAction.prototype.execute = function (evt) {
  54484. this.func(evt);
  54485. };
  54486. return ExecuteCodeAction;
  54487. }(BABYLON.Action));
  54488. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54489. var SetParentAction = /** @class */ (function (_super) {
  54490. __extends(SetParentAction, _super);
  54491. function SetParentAction(triggerOptions, target, parent, condition) {
  54492. var _this = _super.call(this, triggerOptions, condition) || this;
  54493. _this._target = target;
  54494. _this._parent = parent;
  54495. return _this;
  54496. }
  54497. SetParentAction.prototype._prepare = function () {
  54498. };
  54499. SetParentAction.prototype.execute = function () {
  54500. if (this._target.parent === this._parent) {
  54501. return;
  54502. }
  54503. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54504. invertParentWorldMatrix.invert();
  54505. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54506. this._target.parent = this._parent;
  54507. };
  54508. SetParentAction.prototype.serialize = function (parent) {
  54509. return _super.prototype._serialize.call(this, {
  54510. name: "SetParentAction",
  54511. properties: [
  54512. BABYLON.Action._GetTargetProperty(this._target),
  54513. BABYLON.Action._GetTargetProperty(this._parent),
  54514. ]
  54515. }, parent);
  54516. };
  54517. return SetParentAction;
  54518. }(BABYLON.Action));
  54519. BABYLON.SetParentAction = SetParentAction;
  54520. var PlaySoundAction = /** @class */ (function (_super) {
  54521. __extends(PlaySoundAction, _super);
  54522. function PlaySoundAction(triggerOptions, sound, condition) {
  54523. var _this = _super.call(this, triggerOptions, condition) || this;
  54524. _this._sound = sound;
  54525. return _this;
  54526. }
  54527. PlaySoundAction.prototype._prepare = function () {
  54528. };
  54529. PlaySoundAction.prototype.execute = function () {
  54530. if (this._sound !== undefined)
  54531. this._sound.play();
  54532. };
  54533. PlaySoundAction.prototype.serialize = function (parent) {
  54534. return _super.prototype._serialize.call(this, {
  54535. name: "PlaySoundAction",
  54536. properties: [{ name: "sound", value: this._sound.name }]
  54537. }, parent);
  54538. };
  54539. return PlaySoundAction;
  54540. }(BABYLON.Action));
  54541. BABYLON.PlaySoundAction = PlaySoundAction;
  54542. var StopSoundAction = /** @class */ (function (_super) {
  54543. __extends(StopSoundAction, _super);
  54544. function StopSoundAction(triggerOptions, sound, condition) {
  54545. var _this = _super.call(this, triggerOptions, condition) || this;
  54546. _this._sound = sound;
  54547. return _this;
  54548. }
  54549. StopSoundAction.prototype._prepare = function () {
  54550. };
  54551. StopSoundAction.prototype.execute = function () {
  54552. if (this._sound !== undefined)
  54553. this._sound.stop();
  54554. };
  54555. StopSoundAction.prototype.serialize = function (parent) {
  54556. return _super.prototype._serialize.call(this, {
  54557. name: "StopSoundAction",
  54558. properties: [{ name: "sound", value: this._sound.name }]
  54559. }, parent);
  54560. };
  54561. return StopSoundAction;
  54562. }(BABYLON.Action));
  54563. BABYLON.StopSoundAction = StopSoundAction;
  54564. })(BABYLON || (BABYLON = {}));
  54565. //# sourceMappingURL=babylon.directActions.js.map
  54566. var BABYLON;
  54567. (function (BABYLON) {
  54568. var SpriteManager = /** @class */ (function () {
  54569. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54570. if (epsilon === void 0) { epsilon = 0.01; }
  54571. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54572. this.name = name;
  54573. this.sprites = new Array();
  54574. this.renderingGroupId = 0;
  54575. this.layerMask = 0x0FFFFFFF;
  54576. this.fogEnabled = true;
  54577. this.isPickable = false;
  54578. /**
  54579. * An event triggered when the manager is disposed.
  54580. */
  54581. this.onDisposeObservable = new BABYLON.Observable();
  54582. this._vertexBuffers = {};
  54583. this._capacity = capacity;
  54584. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54585. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54586. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54587. if (cellSize.width && cellSize.height) {
  54588. this.cellWidth = cellSize.width;
  54589. this.cellHeight = cellSize.height;
  54590. }
  54591. else if (cellSize !== undefined) {
  54592. this.cellWidth = cellSize;
  54593. this.cellHeight = cellSize;
  54594. }
  54595. else {
  54596. return;
  54597. }
  54598. this._epsilon = epsilon;
  54599. this._scene = scene;
  54600. this._scene.spriteManagers.push(this);
  54601. var indices = [];
  54602. var index = 0;
  54603. for (var count = 0; count < capacity; count++) {
  54604. indices.push(index);
  54605. indices.push(index + 1);
  54606. indices.push(index + 2);
  54607. indices.push(index);
  54608. indices.push(index + 2);
  54609. indices.push(index + 3);
  54610. index += 4;
  54611. }
  54612. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54613. // VBO
  54614. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54615. this._vertexData = new Float32Array(capacity * 16 * 4);
  54616. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54617. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54618. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54619. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54620. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54621. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54622. this._vertexBuffers["options"] = options;
  54623. this._vertexBuffers["cellInfo"] = cellInfo;
  54624. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54625. // Effects
  54626. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54627. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54628. }
  54629. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54630. set: function (callback) {
  54631. if (this._onDisposeObserver) {
  54632. this.onDisposeObservable.remove(this._onDisposeObserver);
  54633. }
  54634. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54635. },
  54636. enumerable: true,
  54637. configurable: true
  54638. });
  54639. Object.defineProperty(SpriteManager.prototype, "texture", {
  54640. get: function () {
  54641. return this._spriteTexture;
  54642. },
  54643. set: function (value) {
  54644. this._spriteTexture = value;
  54645. },
  54646. enumerable: true,
  54647. configurable: true
  54648. });
  54649. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54650. var arrayOffset = index * 16;
  54651. if (offsetX === 0)
  54652. offsetX = this._epsilon;
  54653. else if (offsetX === 1)
  54654. offsetX = 1 - this._epsilon;
  54655. if (offsetY === 0)
  54656. offsetY = this._epsilon;
  54657. else if (offsetY === 1)
  54658. offsetY = 1 - this._epsilon;
  54659. this._vertexData[arrayOffset] = sprite.position.x;
  54660. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54661. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54662. this._vertexData[arrayOffset + 3] = sprite.angle;
  54663. this._vertexData[arrayOffset + 4] = sprite.width;
  54664. this._vertexData[arrayOffset + 5] = sprite.height;
  54665. this._vertexData[arrayOffset + 6] = offsetX;
  54666. this._vertexData[arrayOffset + 7] = offsetY;
  54667. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54668. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54669. var offset = (sprite.cellIndex / rowSize) >> 0;
  54670. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54671. this._vertexData[arrayOffset + 11] = offset;
  54672. // Color
  54673. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54674. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54675. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54676. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54677. };
  54678. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54679. var count = Math.min(this._capacity, this.sprites.length);
  54680. var min = BABYLON.Vector3.Zero();
  54681. var max = BABYLON.Vector3.Zero();
  54682. var distance = Number.MAX_VALUE;
  54683. var currentSprite = null;
  54684. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54685. var cameraView = camera.getViewMatrix();
  54686. for (var index = 0; index < count; index++) {
  54687. var sprite = this.sprites[index];
  54688. if (!sprite) {
  54689. continue;
  54690. }
  54691. if (predicate) {
  54692. if (!predicate(sprite)) {
  54693. continue;
  54694. }
  54695. }
  54696. else if (!sprite.isPickable) {
  54697. continue;
  54698. }
  54699. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54700. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54701. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54702. if (ray.intersectsBoxMinMax(min, max)) {
  54703. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54704. if (distance > currentDistance) {
  54705. distance = currentDistance;
  54706. currentSprite = sprite;
  54707. if (fastCheck) {
  54708. break;
  54709. }
  54710. }
  54711. }
  54712. }
  54713. if (currentSprite) {
  54714. var result = new BABYLON.PickingInfo();
  54715. result.hit = true;
  54716. result.pickedSprite = currentSprite;
  54717. result.distance = distance;
  54718. return result;
  54719. }
  54720. return null;
  54721. };
  54722. SpriteManager.prototype.render = function () {
  54723. // Check
  54724. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54725. return;
  54726. var engine = this._scene.getEngine();
  54727. var baseSize = this._spriteTexture.getBaseSize();
  54728. // Sprites
  54729. var deltaTime = engine.getDeltaTime();
  54730. var max = Math.min(this._capacity, this.sprites.length);
  54731. var rowSize = baseSize.width / this.cellWidth;
  54732. var offset = 0;
  54733. for (var index = 0; index < max; index++) {
  54734. var sprite = this.sprites[index];
  54735. if (!sprite) {
  54736. continue;
  54737. }
  54738. sprite._animate(deltaTime);
  54739. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54740. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54741. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54742. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54743. }
  54744. this._buffer.update(this._vertexData);
  54745. // Render
  54746. var effect = this._effectBase;
  54747. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54748. effect = this._effectFog;
  54749. }
  54750. engine.enableEffect(effect);
  54751. var viewMatrix = this._scene.getViewMatrix();
  54752. effect.setTexture("diffuseSampler", this._spriteTexture);
  54753. effect.setMatrix("view", viewMatrix);
  54754. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54755. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54756. // Fog
  54757. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54758. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54759. effect.setColor3("vFogColor", this._scene.fogColor);
  54760. }
  54761. // VBOs
  54762. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54763. // Draw order
  54764. engine.setDepthFunctionToLessOrEqual();
  54765. effect.setBool("alphaTest", true);
  54766. engine.setColorWrite(false);
  54767. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54768. engine.setColorWrite(true);
  54769. effect.setBool("alphaTest", false);
  54770. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54771. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54772. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54773. };
  54774. SpriteManager.prototype.dispose = function () {
  54775. if (this._buffer) {
  54776. this._buffer.dispose();
  54777. this._buffer = null;
  54778. }
  54779. if (this._indexBuffer) {
  54780. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54781. this._indexBuffer = null;
  54782. }
  54783. if (this._spriteTexture) {
  54784. this._spriteTexture.dispose();
  54785. this._spriteTexture = null;
  54786. }
  54787. // Remove from scene
  54788. var index = this._scene.spriteManagers.indexOf(this);
  54789. this._scene.spriteManagers.splice(index, 1);
  54790. // Callback
  54791. this.onDisposeObservable.notifyObservers(this);
  54792. this.onDisposeObservable.clear();
  54793. };
  54794. return SpriteManager;
  54795. }());
  54796. BABYLON.SpriteManager = SpriteManager;
  54797. })(BABYLON || (BABYLON = {}));
  54798. //# sourceMappingURL=babylon.spriteManager.js.map
  54799. var BABYLON;
  54800. (function (BABYLON) {
  54801. var Sprite = /** @class */ (function () {
  54802. function Sprite(name, manager) {
  54803. this.name = name;
  54804. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54805. this.width = 1.0;
  54806. this.height = 1.0;
  54807. this.angle = 0;
  54808. this.cellIndex = 0;
  54809. this.invertU = 0;
  54810. this.invertV = 0;
  54811. this.animations = new Array();
  54812. this.isPickable = false;
  54813. this._animationStarted = false;
  54814. this._loopAnimation = false;
  54815. this._fromIndex = 0;
  54816. this._toIndex = 0;
  54817. this._delay = 0;
  54818. this._direction = 1;
  54819. this._time = 0;
  54820. this._manager = manager;
  54821. this._manager.sprites.push(this);
  54822. this.position = BABYLON.Vector3.Zero();
  54823. }
  54824. Object.defineProperty(Sprite.prototype, "size", {
  54825. get: function () {
  54826. return this.width;
  54827. },
  54828. set: function (value) {
  54829. this.width = value;
  54830. this.height = value;
  54831. },
  54832. enumerable: true,
  54833. configurable: true
  54834. });
  54835. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54836. this._fromIndex = from;
  54837. this._toIndex = to;
  54838. this._loopAnimation = loop;
  54839. this._delay = delay;
  54840. this._animationStarted = true;
  54841. this._direction = from < to ? 1 : -1;
  54842. this.cellIndex = from;
  54843. this._time = 0;
  54844. this._onAnimationEnd = onAnimationEnd;
  54845. };
  54846. Sprite.prototype.stopAnimation = function () {
  54847. this._animationStarted = false;
  54848. };
  54849. Sprite.prototype._animate = function (deltaTime) {
  54850. if (!this._animationStarted)
  54851. return;
  54852. this._time += deltaTime;
  54853. if (this._time > this._delay) {
  54854. this._time = this._time % this._delay;
  54855. this.cellIndex += this._direction;
  54856. if (this.cellIndex > this._toIndex) {
  54857. if (this._loopAnimation) {
  54858. this.cellIndex = this._fromIndex;
  54859. }
  54860. else {
  54861. this.cellIndex = this._toIndex;
  54862. this._animationStarted = false;
  54863. if (this._onAnimationEnd) {
  54864. this._onAnimationEnd();
  54865. }
  54866. if (this.disposeWhenFinishedAnimating) {
  54867. this.dispose();
  54868. }
  54869. }
  54870. }
  54871. }
  54872. };
  54873. Sprite.prototype.dispose = function () {
  54874. for (var i = 0; i < this._manager.sprites.length; i++) {
  54875. if (this._manager.sprites[i] == this) {
  54876. this._manager.sprites.splice(i, 1);
  54877. }
  54878. }
  54879. };
  54880. return Sprite;
  54881. }());
  54882. BABYLON.Sprite = Sprite;
  54883. })(BABYLON || (BABYLON = {}));
  54884. //# sourceMappingURL=babylon.sprite.js.map
  54885. var BABYLON;
  54886. (function (BABYLON) {
  54887. var IntersectionInfo = /** @class */ (function () {
  54888. function IntersectionInfo(bu, bv, distance) {
  54889. this.bu = bu;
  54890. this.bv = bv;
  54891. this.distance = distance;
  54892. this.faceId = 0;
  54893. this.subMeshId = 0;
  54894. }
  54895. return IntersectionInfo;
  54896. }());
  54897. BABYLON.IntersectionInfo = IntersectionInfo;
  54898. /**
  54899. * Information about the result of picking within a scene
  54900. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54901. */
  54902. var PickingInfo = /** @class */ (function () {
  54903. function PickingInfo() {
  54904. /**
  54905. * If the pick collided with an object
  54906. */
  54907. this.hit = false;
  54908. /**
  54909. * Distance away where the pick collided
  54910. */
  54911. this.distance = 0;
  54912. /**
  54913. * The location of pick collision
  54914. */
  54915. this.pickedPoint = null;
  54916. /**
  54917. * The mesh corrisponding the the pick collision
  54918. */
  54919. this.pickedMesh = null;
  54920. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54921. this.bu = 0;
  54922. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54923. this.bv = 0;
  54924. /** The id of the face on the mesh that was picked */
  54925. this.faceId = -1;
  54926. /** Id of the the submesh that was picked */
  54927. this.subMeshId = 0;
  54928. /** If a sprite was picked, this will be the sprite the pick collided with */
  54929. this.pickedSprite = null;
  54930. /**
  54931. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54932. */
  54933. this.originMesh = null;
  54934. /**
  54935. * The ray that was used to perform the picking.
  54936. */
  54937. this.ray = null;
  54938. }
  54939. /**
  54940. * Gets the normal corrispodning to the face the pick collided with
  54941. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54942. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54943. * @returns The normal corrispodning to the face the pick collided with
  54944. */
  54945. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54946. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54947. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54948. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54949. return null;
  54950. }
  54951. var indices = this.pickedMesh.getIndices();
  54952. if (!indices) {
  54953. return null;
  54954. }
  54955. var result;
  54956. if (useVerticesNormals) {
  54957. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54958. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54959. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54960. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54961. normal0 = normal0.scale(this.bu);
  54962. normal1 = normal1.scale(this.bv);
  54963. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54964. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54965. }
  54966. else {
  54967. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54968. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54969. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54970. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54971. var p1p2 = vertex1.subtract(vertex2);
  54972. var p3p2 = vertex3.subtract(vertex2);
  54973. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54974. }
  54975. if (useWorldCoordinates) {
  54976. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54977. }
  54978. return BABYLON.Vector3.Normalize(result);
  54979. };
  54980. /**
  54981. * Gets the texture coordinates of where the pick occured
  54982. * @returns the vector containing the coordnates of the texture
  54983. */
  54984. PickingInfo.prototype.getTextureCoordinates = function () {
  54985. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54986. return null;
  54987. }
  54988. var indices = this.pickedMesh.getIndices();
  54989. if (!indices) {
  54990. return null;
  54991. }
  54992. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54993. if (!uvs) {
  54994. return null;
  54995. }
  54996. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54997. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54998. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54999. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55000. uv1 = uv1.scale(this.bu);
  55001. uv2 = uv2.scale(this.bv);
  55002. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55003. };
  55004. return PickingInfo;
  55005. }());
  55006. BABYLON.PickingInfo = PickingInfo;
  55007. })(BABYLON || (BABYLON = {}));
  55008. //# sourceMappingURL=babylon.pickingInfo.js.map
  55009. var BABYLON;
  55010. (function (BABYLON) {
  55011. var Ray = /** @class */ (function () {
  55012. function Ray(origin, direction, length) {
  55013. if (length === void 0) { length = Number.MAX_VALUE; }
  55014. this.origin = origin;
  55015. this.direction = direction;
  55016. this.length = length;
  55017. }
  55018. // Methods
  55019. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55020. var d = 0.0;
  55021. var maxValue = Number.MAX_VALUE;
  55022. var inv;
  55023. var min;
  55024. var max;
  55025. var temp;
  55026. if (Math.abs(this.direction.x) < 0.0000001) {
  55027. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55028. return false;
  55029. }
  55030. }
  55031. else {
  55032. inv = 1.0 / this.direction.x;
  55033. min = (minimum.x - this.origin.x) * inv;
  55034. max = (maximum.x - this.origin.x) * inv;
  55035. if (max === -Infinity) {
  55036. max = Infinity;
  55037. }
  55038. if (min > max) {
  55039. temp = min;
  55040. min = max;
  55041. max = temp;
  55042. }
  55043. d = Math.max(min, d);
  55044. maxValue = Math.min(max, maxValue);
  55045. if (d > maxValue) {
  55046. return false;
  55047. }
  55048. }
  55049. if (Math.abs(this.direction.y) < 0.0000001) {
  55050. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55051. return false;
  55052. }
  55053. }
  55054. else {
  55055. inv = 1.0 / this.direction.y;
  55056. min = (minimum.y - this.origin.y) * inv;
  55057. max = (maximum.y - this.origin.y) * inv;
  55058. if (max === -Infinity) {
  55059. max = Infinity;
  55060. }
  55061. if (min > max) {
  55062. temp = min;
  55063. min = max;
  55064. max = temp;
  55065. }
  55066. d = Math.max(min, d);
  55067. maxValue = Math.min(max, maxValue);
  55068. if (d > maxValue) {
  55069. return false;
  55070. }
  55071. }
  55072. if (Math.abs(this.direction.z) < 0.0000001) {
  55073. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55074. return false;
  55075. }
  55076. }
  55077. else {
  55078. inv = 1.0 / this.direction.z;
  55079. min = (minimum.z - this.origin.z) * inv;
  55080. max = (maximum.z - this.origin.z) * inv;
  55081. if (max === -Infinity) {
  55082. max = Infinity;
  55083. }
  55084. if (min > max) {
  55085. temp = min;
  55086. min = max;
  55087. max = temp;
  55088. }
  55089. d = Math.max(min, d);
  55090. maxValue = Math.min(max, maxValue);
  55091. if (d > maxValue) {
  55092. return false;
  55093. }
  55094. }
  55095. return true;
  55096. };
  55097. Ray.prototype.intersectsBox = function (box) {
  55098. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55099. };
  55100. Ray.prototype.intersectsSphere = function (sphere) {
  55101. var x = sphere.center.x - this.origin.x;
  55102. var y = sphere.center.y - this.origin.y;
  55103. var z = sphere.center.z - this.origin.z;
  55104. var pyth = (x * x) + (y * y) + (z * z);
  55105. var rr = sphere.radius * sphere.radius;
  55106. if (pyth <= rr) {
  55107. return true;
  55108. }
  55109. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55110. if (dot < 0.0) {
  55111. return false;
  55112. }
  55113. var temp = pyth - (dot * dot);
  55114. return temp <= rr;
  55115. };
  55116. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55117. if (!this._edge1) {
  55118. this._edge1 = BABYLON.Vector3.Zero();
  55119. this._edge2 = BABYLON.Vector3.Zero();
  55120. this._pvec = BABYLON.Vector3.Zero();
  55121. this._tvec = BABYLON.Vector3.Zero();
  55122. this._qvec = BABYLON.Vector3.Zero();
  55123. }
  55124. vertex1.subtractToRef(vertex0, this._edge1);
  55125. vertex2.subtractToRef(vertex0, this._edge2);
  55126. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55127. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55128. if (det === 0) {
  55129. return null;
  55130. }
  55131. var invdet = 1 / det;
  55132. this.origin.subtractToRef(vertex0, this._tvec);
  55133. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55134. if (bu < 0 || bu > 1.0) {
  55135. return null;
  55136. }
  55137. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55138. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55139. if (bv < 0 || bu + bv > 1.0) {
  55140. return null;
  55141. }
  55142. //check if the distance is longer than the predefined length.
  55143. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55144. if (distance > this.length) {
  55145. return null;
  55146. }
  55147. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55148. };
  55149. Ray.prototype.intersectsPlane = function (plane) {
  55150. var distance;
  55151. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55152. if (Math.abs(result1) < 9.99999997475243E-07) {
  55153. return null;
  55154. }
  55155. else {
  55156. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55157. distance = (-plane.d - result2) / result1;
  55158. if (distance < 0.0) {
  55159. if (distance < -9.99999997475243E-07) {
  55160. return null;
  55161. }
  55162. else {
  55163. return 0;
  55164. }
  55165. }
  55166. return distance;
  55167. }
  55168. };
  55169. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55170. var tm = BABYLON.Tmp.Matrix[0];
  55171. mesh.getWorldMatrix().invertToRef(tm);
  55172. if (this._tmpRay) {
  55173. Ray.TransformToRef(this, tm, this._tmpRay);
  55174. }
  55175. else {
  55176. this._tmpRay = Ray.Transform(this, tm);
  55177. }
  55178. return mesh.intersects(this._tmpRay, fastCheck);
  55179. };
  55180. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55181. if (results) {
  55182. results.length = 0;
  55183. }
  55184. else {
  55185. results = [];
  55186. }
  55187. for (var i = 0; i < meshes.length; i++) {
  55188. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55189. if (pickInfo.hit) {
  55190. results.push(pickInfo);
  55191. }
  55192. }
  55193. results.sort(this._comparePickingInfo);
  55194. return results;
  55195. };
  55196. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55197. if (pickingInfoA.distance < pickingInfoB.distance) {
  55198. return -1;
  55199. }
  55200. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55201. return 1;
  55202. }
  55203. else {
  55204. return 0;
  55205. }
  55206. };
  55207. /**
  55208. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55209. * @param sega the first point of the segment to test the intersection against
  55210. * @param segb the second point of the segment to test the intersection against
  55211. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55212. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55213. */
  55214. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55215. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55216. var u = segb.subtract(sega);
  55217. var v = rsegb.subtract(this.origin);
  55218. var w = sega.subtract(this.origin);
  55219. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55220. var b = BABYLON.Vector3.Dot(u, v);
  55221. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55222. var d = BABYLON.Vector3.Dot(u, w);
  55223. var e = BABYLON.Vector3.Dot(v, w);
  55224. var D = a * c - b * b; // always >= 0
  55225. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55226. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55227. // compute the line parameters of the two closest points
  55228. if (D < Ray.smallnum) { // the lines are almost parallel
  55229. sN = 0.0; // force using point P0 on segment S1
  55230. sD = 1.0; // to prevent possible division by 0.0 later
  55231. tN = e;
  55232. tD = c;
  55233. }
  55234. else { // get the closest points on the infinite lines
  55235. sN = (b * e - c * d);
  55236. tN = (a * e - b * d);
  55237. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55238. sN = 0.0;
  55239. tN = e;
  55240. tD = c;
  55241. }
  55242. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55243. sN = sD;
  55244. tN = e + b;
  55245. tD = c;
  55246. }
  55247. }
  55248. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55249. tN = 0.0;
  55250. // recompute sc for this edge
  55251. if (-d < 0.0) {
  55252. sN = 0.0;
  55253. }
  55254. else if (-d > a)
  55255. sN = sD;
  55256. else {
  55257. sN = -d;
  55258. sD = a;
  55259. }
  55260. }
  55261. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55262. tN = tD;
  55263. // recompute sc for this edge
  55264. if ((-d + b) < 0.0) {
  55265. sN = 0;
  55266. }
  55267. else if ((-d + b) > a) {
  55268. sN = sD;
  55269. }
  55270. else {
  55271. sN = (-d + b);
  55272. sD = a;
  55273. }
  55274. }
  55275. // finally do the division to get sc and tc
  55276. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55277. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55278. // get the difference of the two closest points
  55279. var qtc = v.multiplyByFloats(tc, tc, tc);
  55280. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55281. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55282. if (isIntersected) {
  55283. return qtc.length();
  55284. }
  55285. return -1;
  55286. };
  55287. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55288. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55289. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55290. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55291. this.direction.normalize();
  55292. return this;
  55293. };
  55294. // Statics
  55295. Ray.Zero = function () {
  55296. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55297. };
  55298. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55299. var result = Ray.Zero();
  55300. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55301. };
  55302. /**
  55303. * 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
  55304. * transformed to the given world matrix.
  55305. * @param origin The origin point
  55306. * @param end The end point
  55307. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55308. */
  55309. Ray.CreateNewFromTo = function (origin, end, world) {
  55310. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55311. var direction = end.subtract(origin);
  55312. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55313. direction.normalize();
  55314. return Ray.Transform(new Ray(origin, direction, length), world);
  55315. };
  55316. Ray.Transform = function (ray, matrix) {
  55317. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55318. Ray.TransformToRef(ray, matrix, result);
  55319. return result;
  55320. };
  55321. Ray.TransformToRef = function (ray, matrix, result) {
  55322. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55323. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55324. result.length = ray.length;
  55325. var dir = result.direction;
  55326. var len = dir.length();
  55327. if (!(len === 0 || len === 1)) {
  55328. var num = 1.0 / len;
  55329. dir.x *= num;
  55330. dir.y *= num;
  55331. dir.z *= num;
  55332. result.length *= len;
  55333. }
  55334. };
  55335. Ray.smallnum = 0.00000001;
  55336. Ray.rayl = 10e8;
  55337. return Ray;
  55338. }());
  55339. BABYLON.Ray = Ray;
  55340. })(BABYLON || (BABYLON = {}));
  55341. //# sourceMappingURL=babylon.ray.js.map
  55342. var BABYLON;
  55343. (function (BABYLON) {
  55344. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55345. if (boxMin.x > sphereCenter.x + sphereRadius)
  55346. return false;
  55347. if (sphereCenter.x - sphereRadius > boxMax.x)
  55348. return false;
  55349. if (boxMin.y > sphereCenter.y + sphereRadius)
  55350. return false;
  55351. if (sphereCenter.y - sphereRadius > boxMax.y)
  55352. return false;
  55353. if (boxMin.z > sphereCenter.z + sphereRadius)
  55354. return false;
  55355. if (sphereCenter.z - sphereRadius > boxMax.z)
  55356. return false;
  55357. return true;
  55358. };
  55359. var getLowestRoot = (function () {
  55360. var result = { root: 0, found: false };
  55361. return function (a, b, c, maxR) {
  55362. result.root = 0;
  55363. result.found = false;
  55364. var determinant = b * b - 4.0 * a * c;
  55365. if (determinant < 0)
  55366. return result;
  55367. var sqrtD = Math.sqrt(determinant);
  55368. var r1 = (-b - sqrtD) / (2.0 * a);
  55369. var r2 = (-b + sqrtD) / (2.0 * a);
  55370. if (r1 > r2) {
  55371. var temp = r2;
  55372. r2 = r1;
  55373. r1 = temp;
  55374. }
  55375. if (r1 > 0 && r1 < maxR) {
  55376. result.root = r1;
  55377. result.found = true;
  55378. return result;
  55379. }
  55380. if (r2 > 0 && r2 < maxR) {
  55381. result.root = r2;
  55382. result.found = true;
  55383. return result;
  55384. }
  55385. return result;
  55386. };
  55387. })();
  55388. var Collider = /** @class */ (function () {
  55389. function Collider() {
  55390. this._collisionPoint = BABYLON.Vector3.Zero();
  55391. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55392. this._tempVector = BABYLON.Vector3.Zero();
  55393. this._tempVector2 = BABYLON.Vector3.Zero();
  55394. this._tempVector3 = BABYLON.Vector3.Zero();
  55395. this._tempVector4 = BABYLON.Vector3.Zero();
  55396. this._edge = BABYLON.Vector3.Zero();
  55397. this._baseToVertex = BABYLON.Vector3.Zero();
  55398. this._destinationPoint = BABYLON.Vector3.Zero();
  55399. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55400. this._displacementVector = BABYLON.Vector3.Zero();
  55401. this._radius = BABYLON.Vector3.One();
  55402. this._retry = 0;
  55403. this._basePointWorld = BABYLON.Vector3.Zero();
  55404. this._velocityWorld = BABYLON.Vector3.Zero();
  55405. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55406. this._collisionMask = -1;
  55407. }
  55408. Object.defineProperty(Collider.prototype, "collisionMask", {
  55409. get: function () {
  55410. return this._collisionMask;
  55411. },
  55412. set: function (mask) {
  55413. this._collisionMask = !isNaN(mask) ? mask : -1;
  55414. },
  55415. enumerable: true,
  55416. configurable: true
  55417. });
  55418. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55419. /**
  55420. * Gets the plane normal used to compute the sliding response (in local space)
  55421. */
  55422. get: function () {
  55423. return this._slidePlaneNormal;
  55424. },
  55425. enumerable: true,
  55426. configurable: true
  55427. });
  55428. // Methods
  55429. Collider.prototype._initialize = function (source, dir, e) {
  55430. this._velocity = dir;
  55431. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55432. this._basePoint = source;
  55433. source.multiplyToRef(this._radius, this._basePointWorld);
  55434. dir.multiplyToRef(this._radius, this._velocityWorld);
  55435. this._velocityWorldLength = this._velocityWorld.length();
  55436. this._epsilon = e;
  55437. this.collisionFound = false;
  55438. };
  55439. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55440. pa.subtractToRef(point, this._tempVector);
  55441. pb.subtractToRef(point, this._tempVector2);
  55442. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55443. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55444. if (d < 0)
  55445. return false;
  55446. pc.subtractToRef(point, this._tempVector3);
  55447. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55448. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55449. if (d < 0)
  55450. return false;
  55451. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55452. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55453. return d >= 0;
  55454. };
  55455. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55456. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55457. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55458. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55459. return false;
  55460. }
  55461. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55462. return false;
  55463. return true;
  55464. };
  55465. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55466. var t0;
  55467. var embeddedInPlane = false;
  55468. //defensive programming, actually not needed.
  55469. if (!trianglePlaneArray) {
  55470. trianglePlaneArray = [];
  55471. }
  55472. if (!trianglePlaneArray[faceIndex]) {
  55473. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55474. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55475. }
  55476. var trianglePlane = trianglePlaneArray[faceIndex];
  55477. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55478. return;
  55479. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55480. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55481. if (normalDotVelocity == 0) {
  55482. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55483. return;
  55484. embeddedInPlane = true;
  55485. t0 = 0;
  55486. }
  55487. else {
  55488. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55489. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55490. if (t0 > t1) {
  55491. var temp = t1;
  55492. t1 = t0;
  55493. t0 = temp;
  55494. }
  55495. if (t0 > 1.0 || t1 < 0.0)
  55496. return;
  55497. if (t0 < 0)
  55498. t0 = 0;
  55499. if (t0 > 1.0)
  55500. t0 = 1.0;
  55501. }
  55502. this._collisionPoint.copyFromFloats(0, 0, 0);
  55503. var found = false;
  55504. var t = 1.0;
  55505. if (!embeddedInPlane) {
  55506. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55507. this._velocity.scaleToRef(t0, this._tempVector);
  55508. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55509. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55510. found = true;
  55511. t = t0;
  55512. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55513. }
  55514. }
  55515. if (!found) {
  55516. var velocitySquaredLength = this._velocity.lengthSquared();
  55517. var a = velocitySquaredLength;
  55518. this._basePoint.subtractToRef(p1, this._tempVector);
  55519. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55520. var c = this._tempVector.lengthSquared() - 1.0;
  55521. var lowestRoot = getLowestRoot(a, b, c, t);
  55522. if (lowestRoot.found) {
  55523. t = lowestRoot.root;
  55524. found = true;
  55525. this._collisionPoint.copyFrom(p1);
  55526. }
  55527. this._basePoint.subtractToRef(p2, this._tempVector);
  55528. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55529. c = this._tempVector.lengthSquared() - 1.0;
  55530. lowestRoot = getLowestRoot(a, b, c, t);
  55531. if (lowestRoot.found) {
  55532. t = lowestRoot.root;
  55533. found = true;
  55534. this._collisionPoint.copyFrom(p2);
  55535. }
  55536. this._basePoint.subtractToRef(p3, this._tempVector);
  55537. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55538. c = this._tempVector.lengthSquared() - 1.0;
  55539. lowestRoot = getLowestRoot(a, b, c, t);
  55540. if (lowestRoot.found) {
  55541. t = lowestRoot.root;
  55542. found = true;
  55543. this._collisionPoint.copyFrom(p3);
  55544. }
  55545. p2.subtractToRef(p1, this._edge);
  55546. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55547. var edgeSquaredLength = this._edge.lengthSquared();
  55548. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55549. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55550. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55551. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55552. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55553. lowestRoot = getLowestRoot(a, b, c, t);
  55554. if (lowestRoot.found) {
  55555. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55556. if (f >= 0.0 && f <= 1.0) {
  55557. t = lowestRoot.root;
  55558. found = true;
  55559. this._edge.scaleInPlace(f);
  55560. p1.addToRef(this._edge, this._collisionPoint);
  55561. }
  55562. }
  55563. p3.subtractToRef(p2, this._edge);
  55564. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55565. edgeSquaredLength = this._edge.lengthSquared();
  55566. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55567. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55568. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55569. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55570. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55571. lowestRoot = getLowestRoot(a, b, c, t);
  55572. if (lowestRoot.found) {
  55573. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55574. if (f >= 0.0 && f <= 1.0) {
  55575. t = lowestRoot.root;
  55576. found = true;
  55577. this._edge.scaleInPlace(f);
  55578. p2.addToRef(this._edge, this._collisionPoint);
  55579. }
  55580. }
  55581. p1.subtractToRef(p3, this._edge);
  55582. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55583. edgeSquaredLength = this._edge.lengthSquared();
  55584. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55585. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55586. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55587. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55588. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55589. lowestRoot = getLowestRoot(a, b, c, t);
  55590. if (lowestRoot.found) {
  55591. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55592. if (f >= 0.0 && f <= 1.0) {
  55593. t = lowestRoot.root;
  55594. found = true;
  55595. this._edge.scaleInPlace(f);
  55596. p3.addToRef(this._edge, this._collisionPoint);
  55597. }
  55598. }
  55599. }
  55600. if (found) {
  55601. var distToCollision = t * this._velocity.length();
  55602. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55603. if (!this.intersectionPoint) {
  55604. this.intersectionPoint = this._collisionPoint.clone();
  55605. }
  55606. else {
  55607. this.intersectionPoint.copyFrom(this._collisionPoint);
  55608. }
  55609. this._nearestDistance = distToCollision;
  55610. this.collisionFound = true;
  55611. }
  55612. }
  55613. };
  55614. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55615. for (var i = indexStart; i < indexEnd; i += 3) {
  55616. var p1 = pts[indices[i] - decal];
  55617. var p2 = pts[indices[i + 1] - decal];
  55618. var p3 = pts[indices[i + 2] - decal];
  55619. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55620. }
  55621. };
  55622. Collider.prototype._getResponse = function (pos, vel) {
  55623. pos.addToRef(vel, this._destinationPoint);
  55624. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55625. this._basePoint.addToRef(vel, pos);
  55626. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55627. this._slidePlaneNormal.normalize();
  55628. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55629. pos.addInPlace(this._displacementVector);
  55630. this.intersectionPoint.addInPlace(this._displacementVector);
  55631. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55632. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55633. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55634. };
  55635. return Collider;
  55636. }());
  55637. BABYLON.Collider = Collider;
  55638. })(BABYLON || (BABYLON = {}));
  55639. //# sourceMappingURL=babylon.collider.js.map
  55640. var BABYLON;
  55641. (function (BABYLON) {
  55642. //WebWorker code will be inserted to this variable.
  55643. BABYLON.CollisionWorker = "";
  55644. /** Defines supported task for worker process */
  55645. var WorkerTaskType;
  55646. (function (WorkerTaskType) {
  55647. /** Initialization */
  55648. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55649. /** Update of geometry */
  55650. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55651. /** Evaluate collision */
  55652. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55653. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55654. /** Defines kind of replies returned by worker */
  55655. var WorkerReplyType;
  55656. (function (WorkerReplyType) {
  55657. /** Success */
  55658. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55659. /** Unkown error */
  55660. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55661. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55662. var CollisionCoordinatorWorker = /** @class */ (function () {
  55663. function CollisionCoordinatorWorker() {
  55664. var _this = this;
  55665. this._scaledPosition = BABYLON.Vector3.Zero();
  55666. this._scaledVelocity = BABYLON.Vector3.Zero();
  55667. this.onMeshUpdated = function (transformNode) {
  55668. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55669. };
  55670. this.onGeometryUpdated = function (geometry) {
  55671. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55672. };
  55673. this._afterRender = function () {
  55674. if (!_this._init)
  55675. return;
  55676. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55677. return;
  55678. }
  55679. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55680. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55681. if (_this._runningUpdated > 4) {
  55682. return;
  55683. }
  55684. ++_this._runningUpdated;
  55685. var payload = {
  55686. updatedMeshes: _this._addUpdateMeshesList,
  55687. updatedGeometries: _this._addUpdateGeometriesList,
  55688. removedGeometries: _this._toRemoveGeometryArray,
  55689. removedMeshes: _this._toRemoveMeshesArray
  55690. };
  55691. var message = {
  55692. payload: payload,
  55693. taskType: WorkerTaskType.UPDATE
  55694. };
  55695. var serializable = [];
  55696. for (var id in payload.updatedGeometries) {
  55697. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55698. //prepare transferables
  55699. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55700. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55701. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55702. }
  55703. }
  55704. _this._worker.postMessage(message, serializable);
  55705. _this._addUpdateMeshesList = {};
  55706. _this._addUpdateGeometriesList = {};
  55707. _this._toRemoveGeometryArray = [];
  55708. _this._toRemoveMeshesArray = [];
  55709. };
  55710. this._onMessageFromWorker = function (e) {
  55711. var returnData = e.data;
  55712. if (returnData.error != WorkerReplyType.SUCCESS) {
  55713. //TODO what errors can be returned from the worker?
  55714. BABYLON.Tools.Warn("error returned from worker!");
  55715. return;
  55716. }
  55717. switch (returnData.taskType) {
  55718. case WorkerTaskType.INIT:
  55719. _this._init = true;
  55720. //Update the worked with ALL of the scene's current state
  55721. _this._scene.meshes.forEach(function (mesh) {
  55722. _this.onMeshAdded(mesh);
  55723. });
  55724. _this._scene.getGeometries().forEach(function (geometry) {
  55725. _this.onGeometryAdded(geometry);
  55726. });
  55727. break;
  55728. case WorkerTaskType.UPDATE:
  55729. _this._runningUpdated--;
  55730. break;
  55731. case WorkerTaskType.COLLIDE:
  55732. var returnPayload = returnData.payload;
  55733. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55734. return;
  55735. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55736. if (callback) {
  55737. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55738. if (mesh) {
  55739. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55740. }
  55741. }
  55742. //cleanup
  55743. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55744. break;
  55745. }
  55746. };
  55747. this._collisionsCallbackArray = [];
  55748. this._init = false;
  55749. this._runningUpdated = 0;
  55750. this._addUpdateMeshesList = {};
  55751. this._addUpdateGeometriesList = {};
  55752. this._toRemoveGeometryArray = [];
  55753. this._toRemoveMeshesArray = [];
  55754. }
  55755. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55756. if (!this._init)
  55757. return;
  55758. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55759. return;
  55760. position.divideToRef(collider._radius, this._scaledPosition);
  55761. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55762. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55763. var payload = {
  55764. collider: {
  55765. position: this._scaledPosition.asArray(),
  55766. velocity: this._scaledVelocity.asArray(),
  55767. radius: collider._radius.asArray()
  55768. },
  55769. collisionId: collisionIndex,
  55770. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55771. maximumRetry: maximumRetry
  55772. };
  55773. var message = {
  55774. payload: payload,
  55775. taskType: WorkerTaskType.COLLIDE
  55776. };
  55777. this._worker.postMessage(message);
  55778. };
  55779. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55780. this._scene = scene;
  55781. this._scene.registerAfterRender(this._afterRender);
  55782. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55783. this._worker = new Worker(workerUrl);
  55784. this._worker.onmessage = this._onMessageFromWorker;
  55785. var message = {
  55786. payload: {},
  55787. taskType: WorkerTaskType.INIT
  55788. };
  55789. this._worker.postMessage(message);
  55790. };
  55791. CollisionCoordinatorWorker.prototype.destroy = function () {
  55792. this._scene.unregisterAfterRender(this._afterRender);
  55793. this._worker.terminate();
  55794. };
  55795. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55796. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55797. this.onMeshUpdated(mesh);
  55798. };
  55799. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55800. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55801. };
  55802. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55803. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55804. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55805. this.onGeometryUpdated(geometry);
  55806. };
  55807. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55808. this._toRemoveGeometryArray.push(geometry.id);
  55809. };
  55810. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55811. var submeshes = [];
  55812. if (mesh.subMeshes) {
  55813. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55814. var boundingInfo = sm.getBoundingInfo();
  55815. return {
  55816. position: idx,
  55817. verticesStart: sm.verticesStart,
  55818. verticesCount: sm.verticesCount,
  55819. indexStart: sm.indexStart,
  55820. indexCount: sm.indexCount,
  55821. hasMaterial: !!sm.getMaterial(),
  55822. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55823. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55824. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55825. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55826. };
  55827. });
  55828. }
  55829. var geometryId = null;
  55830. if (mesh instanceof BABYLON.Mesh) {
  55831. var geometry = mesh.geometry;
  55832. geometryId = geometry ? geometry.id : null;
  55833. }
  55834. else if (mesh instanceof BABYLON.InstancedMesh) {
  55835. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55836. geometryId = geometry ? geometry.id : null;
  55837. }
  55838. var boundingInfo = mesh.getBoundingInfo();
  55839. return {
  55840. uniqueId: mesh.uniqueId,
  55841. id: mesh.id,
  55842. name: mesh.name,
  55843. geometryId: geometryId,
  55844. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55845. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55846. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55847. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55848. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55849. subMeshes: submeshes,
  55850. checkCollisions: mesh.checkCollisions
  55851. };
  55852. };
  55853. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55854. return {
  55855. id: geometry.id,
  55856. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55857. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55858. indices: new Uint32Array(geometry.getIndices() || []),
  55859. };
  55860. };
  55861. return CollisionCoordinatorWorker;
  55862. }());
  55863. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55864. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55865. function CollisionCoordinatorLegacy() {
  55866. this._scaledPosition = BABYLON.Vector3.Zero();
  55867. this._scaledVelocity = BABYLON.Vector3.Zero();
  55868. this._finalPosition = BABYLON.Vector3.Zero();
  55869. }
  55870. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55871. position.divideToRef(collider._radius, this._scaledPosition);
  55872. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55873. collider.collidedMesh = null;
  55874. collider._retry = 0;
  55875. collider._initialVelocity = this._scaledVelocity;
  55876. collider._initialPosition = this._scaledPosition;
  55877. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55878. this._finalPosition.multiplyInPlace(collider._radius);
  55879. //run the callback
  55880. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55881. };
  55882. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55883. this._scene = scene;
  55884. };
  55885. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55886. //Legacy need no destruction method.
  55887. };
  55888. //No update in legacy mode
  55889. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55890. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55891. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55892. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55893. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55894. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55895. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55896. if (excludedMesh === void 0) { excludedMesh = null; }
  55897. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55898. if (collider._retry >= maximumRetry) {
  55899. finalPosition.copyFrom(position);
  55900. return;
  55901. }
  55902. // Check if this is a mesh else camera or -1
  55903. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55904. collider._initialize(position, velocity, closeDistance);
  55905. // Check all meshes
  55906. for (var index = 0; index < this._scene.meshes.length; index++) {
  55907. var mesh = this._scene.meshes[index];
  55908. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55909. mesh._checkCollision(collider);
  55910. }
  55911. }
  55912. if (!collider.collisionFound) {
  55913. position.addToRef(velocity, finalPosition);
  55914. return;
  55915. }
  55916. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55917. collider._getResponse(position, velocity);
  55918. }
  55919. if (velocity.length() <= closeDistance) {
  55920. finalPosition.copyFrom(position);
  55921. return;
  55922. }
  55923. collider._retry++;
  55924. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55925. };
  55926. return CollisionCoordinatorLegacy;
  55927. }());
  55928. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55929. })(BABYLON || (BABYLON = {}));
  55930. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55931. var BABYLON;
  55932. (function (BABYLON) {
  55933. /**
  55934. * A particle represents one of the element emitted by a particle system.
  55935. * This is mainly define by its coordinates, direction, velocity and age.
  55936. */
  55937. var Particle = /** @class */ (function () {
  55938. /**
  55939. * Creates a new instance Particle
  55940. * @param particleSystem the particle system the particle belongs to
  55941. */
  55942. function Particle(
  55943. /**
  55944. * particleSystem the particle system the particle belongs to.
  55945. */
  55946. particleSystem) {
  55947. this.particleSystem = particleSystem;
  55948. /**
  55949. * The world position of the particle in the scene.
  55950. */
  55951. this.position = BABYLON.Vector3.Zero();
  55952. /**
  55953. * The world direction of the particle in the scene.
  55954. */
  55955. this.direction = BABYLON.Vector3.Zero();
  55956. /**
  55957. * The color of the particle.
  55958. */
  55959. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55960. /**
  55961. * The color change of the particle per step.
  55962. */
  55963. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55964. /**
  55965. * Defines how long will the life of the particle be.
  55966. */
  55967. this.lifeTime = 1.0;
  55968. /**
  55969. * The current age of the particle.
  55970. */
  55971. this.age = 0;
  55972. /**
  55973. * The current size of the particle.
  55974. */
  55975. this.size = 0;
  55976. /**
  55977. * The current angle of the particle.
  55978. */
  55979. this.angle = 0;
  55980. /**
  55981. * Defines how fast is the angle changing.
  55982. */
  55983. this.angularSpeed = 0;
  55984. /**
  55985. * Defines the cell index used by the particle to be rendered from a sprite.
  55986. */
  55987. this.cellIndex = 0;
  55988. this._currentFrameCounter = 0;
  55989. if (!this.particleSystem.isAnimationSheetEnabled) {
  55990. return;
  55991. }
  55992. this.updateCellInfoFromSystem();
  55993. }
  55994. Particle.prototype.updateCellInfoFromSystem = function () {
  55995. this.cellIndex = this.particleSystem.startSpriteCellID;
  55996. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55997. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55998. }
  55999. else {
  56000. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56001. }
  56002. };
  56003. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56004. // (ageOffset / scaledUpdateSpeed) / available cells
  56005. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56006. this._currentFrameCounter += scaledUpdateSpeed;
  56007. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56008. this._currentFrameCounter = 0;
  56009. this.cellIndex++;
  56010. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56011. this.cellIndex = this.particleSystem.endSpriteCellID;
  56012. }
  56013. }
  56014. };
  56015. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56016. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56017. this.cellIndex++;
  56018. this._currentFrameCounter = 0;
  56019. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56020. if (this.particleSystem.spriteCellLoop) {
  56021. this.cellIndex = this.particleSystem.startSpriteCellID;
  56022. }
  56023. else {
  56024. this.cellIndex = this.particleSystem.endSpriteCellID;
  56025. }
  56026. }
  56027. }
  56028. else {
  56029. this._currentFrameCounter++;
  56030. }
  56031. };
  56032. /**
  56033. * Copy the properties of particle to another one.
  56034. * @param other the particle to copy the information to.
  56035. */
  56036. Particle.prototype.copyTo = function (other) {
  56037. other.position.copyFrom(this.position);
  56038. other.direction.copyFrom(this.direction);
  56039. other.color.copyFrom(this.color);
  56040. other.colorStep.copyFrom(this.colorStep);
  56041. other.lifeTime = this.lifeTime;
  56042. other.age = this.age;
  56043. other.size = this.size;
  56044. other.angle = this.angle;
  56045. other.angularSpeed = this.angularSpeed;
  56046. other.particleSystem = this.particleSystem;
  56047. other.cellIndex = this.cellIndex;
  56048. };
  56049. return Particle;
  56050. }());
  56051. BABYLON.Particle = Particle;
  56052. })(BABYLON || (BABYLON = {}));
  56053. //# sourceMappingURL=babylon.particle.js.map
  56054. var BABYLON;
  56055. (function (BABYLON) {
  56056. /**
  56057. * This represents a particle system in Babylon.
  56058. * 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.
  56059. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56060. * @example https://doc.babylonjs.com/babylon101/particles
  56061. */
  56062. var ParticleSystem = /** @class */ (function () {
  56063. /**
  56064. * Instantiates a particle system.
  56065. * 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.
  56066. * @param name The name of the particle system
  56067. * @param capacity The max number of particles alive at the same time
  56068. * @param scene The scene the particle system belongs to
  56069. * @param customEffect a custom effect used to change the way particles are rendered by default
  56070. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56071. * @param epsilon Offset used to render the particles
  56072. */
  56073. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56074. if (customEffect === void 0) { customEffect = null; }
  56075. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56076. if (epsilon === void 0) { epsilon = 0.01; }
  56077. var _this = this;
  56078. /**
  56079. * List of animations used by the particle system.
  56080. */
  56081. this.animations = [];
  56082. /**
  56083. * The rendering group used by the Particle system to chose when to render.
  56084. */
  56085. this.renderingGroupId = 0;
  56086. /**
  56087. * The emitter represents the Mesh or position we are attaching the particle system to.
  56088. */
  56089. this.emitter = null;
  56090. /**
  56091. * The maximum number of particles to emit per frame
  56092. */
  56093. this.emitRate = 10;
  56094. /**
  56095. * If you want to launch only a few particles at once, that can be done, as well.
  56096. */
  56097. this.manualEmitCount = -1;
  56098. /**
  56099. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56100. */
  56101. this.updateSpeed = 0.01;
  56102. /**
  56103. * The amount of time the particle system is running (depends of the overall update speed).
  56104. */
  56105. this.targetStopDuration = 0;
  56106. /**
  56107. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56108. */
  56109. this.disposeOnStop = false;
  56110. /**
  56111. * Minimum power of emitting particles.
  56112. */
  56113. this.minEmitPower = 1;
  56114. /**
  56115. * Maximum power of emitting particles.
  56116. */
  56117. this.maxEmitPower = 1;
  56118. /**
  56119. * Minimum life time of emitting particles.
  56120. */
  56121. this.minLifeTime = 1;
  56122. /**
  56123. * Maximum life time of emitting particles.
  56124. */
  56125. this.maxLifeTime = 1;
  56126. /**
  56127. * Minimum Size of emitting particles.
  56128. */
  56129. this.minSize = 1;
  56130. /**
  56131. * Maximum Size of emitting particles.
  56132. */
  56133. this.maxSize = 1;
  56134. /**
  56135. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56136. */
  56137. this.minAngularSpeed = 0;
  56138. /**
  56139. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56140. */
  56141. this.maxAngularSpeed = 0;
  56142. /**
  56143. * The layer mask we are rendering the particles through.
  56144. */
  56145. this.layerMask = 0x0FFFFFFF;
  56146. /**
  56147. * This can help using your own shader to render the particle system.
  56148. * The according effect will be created
  56149. */
  56150. this.customShader = null;
  56151. /**
  56152. * By default particle system starts as soon as they are created. This prevents the
  56153. * automatic start to happen and let you decide when to start emitting particles.
  56154. */
  56155. this.preventAutoStart = false;
  56156. /**
  56157. * Callback triggered when the particle animation is ending.
  56158. */
  56159. this.onAnimationEnd = null;
  56160. /**
  56161. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56162. */
  56163. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56164. /**
  56165. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56166. * to override the particles.
  56167. */
  56168. this.forceDepthWrite = false;
  56169. /**
  56170. * You can use gravity if you want to give an orientation to your particles.
  56171. */
  56172. this.gravity = BABYLON.Vector3.Zero();
  56173. /**
  56174. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56175. */
  56176. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56177. /**
  56178. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56179. */
  56180. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56181. /**
  56182. * Color the particle will have at the end of its lifetime.
  56183. */
  56184. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56185. /**
  56186. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56187. */
  56188. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56189. /**
  56190. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56191. */
  56192. this.spriteCellLoop = true;
  56193. /**
  56194. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56195. */
  56196. this.spriteCellChangeSpeed = 0;
  56197. /**
  56198. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56199. */
  56200. this.startSpriteCellID = 0;
  56201. /**
  56202. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56203. */
  56204. this.endSpriteCellID = 0;
  56205. /**
  56206. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56207. */
  56208. this.spriteCellWidth = 0;
  56209. /**
  56210. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56211. */
  56212. this.spriteCellHeight = 0;
  56213. /**
  56214. * An event triggered when the system is disposed.
  56215. */
  56216. this.onDisposeObservable = new BABYLON.Observable();
  56217. this._particles = new Array();
  56218. this._stockParticles = new Array();
  56219. this._newPartsExcess = 0;
  56220. this._vertexBuffers = {};
  56221. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56222. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56223. this._scaledDirection = BABYLON.Vector3.Zero();
  56224. this._scaledGravity = BABYLON.Vector3.Zero();
  56225. this._currentRenderId = -1;
  56226. this._started = false;
  56227. this._stopped = false;
  56228. this._actualFrame = 0;
  56229. this._vertexBufferSize = 11;
  56230. // start of sub system methods
  56231. /**
  56232. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56233. * Its lifetime will start back at 0.
  56234. */
  56235. this.recycleParticle = function (particle) {
  56236. var lastParticle = _this._particles.pop();
  56237. if (lastParticle !== particle) {
  56238. lastParticle.copyTo(particle);
  56239. }
  56240. _this._stockParticles.push(lastParticle);
  56241. };
  56242. this._createParticle = function () {
  56243. var particle;
  56244. if (_this._stockParticles.length !== 0) {
  56245. particle = _this._stockParticles.pop();
  56246. particle.age = 0;
  56247. particle.cellIndex = _this.startSpriteCellID;
  56248. }
  56249. else {
  56250. particle = new BABYLON.Particle(_this);
  56251. }
  56252. return particle;
  56253. };
  56254. this._emitFromParticle = function (particle) {
  56255. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56256. return;
  56257. }
  56258. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56259. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56260. subSystem._rootParticleSystem = _this;
  56261. _this.activeSubSystems.push(subSystem);
  56262. subSystem.start();
  56263. };
  56264. this._appendParticleVertexes = null;
  56265. this.id = name;
  56266. this.name = name;
  56267. this._capacity = capacity;
  56268. this._epsilon = epsilon;
  56269. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56270. if (isAnimationSheetEnabled) {
  56271. this._vertexBufferSize = 12;
  56272. }
  56273. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56274. this._customEffect = customEffect;
  56275. scene.particleSystems.push(this);
  56276. this._createIndexBuffer();
  56277. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56278. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56279. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56280. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56281. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56282. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56283. if (this._isAnimationSheetEnabled) {
  56284. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56285. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56286. }
  56287. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56288. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56289. this._vertexBuffers["options"] = options;
  56290. // Default emitter type
  56291. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56292. this.updateFunction = function (particles) {
  56293. for (var index = 0; index < particles.length; index++) {
  56294. var particle = particles[index];
  56295. particle.age += _this._scaledUpdateSpeed;
  56296. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56297. _this._emitFromParticle(particle);
  56298. _this.recycleParticle(particle);
  56299. index--;
  56300. continue;
  56301. }
  56302. else {
  56303. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56304. particle.color.addInPlace(_this._scaledColorStep);
  56305. if (particle.color.a < 0)
  56306. particle.color.a = 0;
  56307. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56308. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56309. particle.position.addInPlace(_this._scaledDirection);
  56310. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56311. particle.direction.addInPlace(_this._scaledGravity);
  56312. if (_this._isAnimationSheetEnabled) {
  56313. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56314. }
  56315. }
  56316. }
  56317. };
  56318. }
  56319. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56320. /**
  56321. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56322. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56323. */
  56324. get: function () {
  56325. if (this.particleEmitterType.direction1) {
  56326. return this.particleEmitterType.direction1;
  56327. }
  56328. return BABYLON.Vector3.Zero();
  56329. },
  56330. set: function (value) {
  56331. if (this.particleEmitterType.direction1) {
  56332. this.particleEmitterType.direction1 = value;
  56333. }
  56334. },
  56335. enumerable: true,
  56336. configurable: true
  56337. });
  56338. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56339. /**
  56340. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56341. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56342. */
  56343. get: function () {
  56344. if (this.particleEmitterType.direction2) {
  56345. return this.particleEmitterType.direction2;
  56346. }
  56347. return BABYLON.Vector3.Zero();
  56348. },
  56349. set: function (value) {
  56350. if (this.particleEmitterType.direction2) {
  56351. this.particleEmitterType.direction2 = value;
  56352. }
  56353. },
  56354. enumerable: true,
  56355. configurable: true
  56356. });
  56357. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56358. /**
  56359. * 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.
  56360. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56361. */
  56362. get: function () {
  56363. if (this.particleEmitterType.minEmitBox) {
  56364. return this.particleEmitterType.minEmitBox;
  56365. }
  56366. return BABYLON.Vector3.Zero();
  56367. },
  56368. set: function (value) {
  56369. if (this.particleEmitterType.minEmitBox) {
  56370. this.particleEmitterType.minEmitBox = value;
  56371. }
  56372. },
  56373. enumerable: true,
  56374. configurable: true
  56375. });
  56376. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56377. /**
  56378. * 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.
  56379. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56380. */
  56381. get: function () {
  56382. if (this.particleEmitterType.maxEmitBox) {
  56383. return this.particleEmitterType.maxEmitBox;
  56384. }
  56385. return BABYLON.Vector3.Zero();
  56386. },
  56387. set: function (value) {
  56388. if (this.particleEmitterType.maxEmitBox) {
  56389. this.particleEmitterType.maxEmitBox = value;
  56390. }
  56391. },
  56392. enumerable: true,
  56393. configurable: true
  56394. });
  56395. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56396. /**
  56397. * Sets a callback that will be triggered when the system is disposed.
  56398. */
  56399. set: function (callback) {
  56400. if (this._onDisposeObserver) {
  56401. this.onDisposeObservable.remove(this._onDisposeObserver);
  56402. }
  56403. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56404. },
  56405. enumerable: true,
  56406. configurable: true
  56407. });
  56408. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56409. /**
  56410. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56411. */
  56412. get: function () {
  56413. return this._isAnimationSheetEnabled;
  56414. },
  56415. enumerable: true,
  56416. configurable: true
  56417. });
  56418. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56419. //end of Sub-emitter
  56420. /**
  56421. * Gets the current list of active particles
  56422. */
  56423. get: function () {
  56424. return this._particles;
  56425. },
  56426. enumerable: true,
  56427. configurable: true
  56428. });
  56429. /**
  56430. * Returns the string "ParticleSystem"
  56431. * @returns a string containing the class name
  56432. */
  56433. ParticleSystem.prototype.getClassName = function () {
  56434. return "ParticleSystem";
  56435. };
  56436. ParticleSystem.prototype._createIndexBuffer = function () {
  56437. var indices = [];
  56438. var index = 0;
  56439. for (var count = 0; count < this._capacity; count++) {
  56440. indices.push(index);
  56441. indices.push(index + 1);
  56442. indices.push(index + 2);
  56443. indices.push(index);
  56444. indices.push(index + 2);
  56445. indices.push(index + 3);
  56446. index += 4;
  56447. }
  56448. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56449. };
  56450. /**
  56451. * Gets the maximum number of particles active at the same time.
  56452. * @returns The max number of active particles.
  56453. */
  56454. ParticleSystem.prototype.getCapacity = function () {
  56455. return this._capacity;
  56456. };
  56457. /**
  56458. * Gets Wether there are still active particles in the system.
  56459. * @returns True if it is alive, otherwise false.
  56460. */
  56461. ParticleSystem.prototype.isAlive = function () {
  56462. return this._alive;
  56463. };
  56464. /**
  56465. * Gets Wether the system has been started.
  56466. * @returns True if it has been started, otherwise false.
  56467. */
  56468. ParticleSystem.prototype.isStarted = function () {
  56469. return this._started;
  56470. };
  56471. /**
  56472. * Starts the particle system and begins to emit.
  56473. */
  56474. ParticleSystem.prototype.start = function () {
  56475. this._started = true;
  56476. this._stopped = false;
  56477. this._actualFrame = 0;
  56478. if (this.subEmitters && this.subEmitters.length != 0) {
  56479. this.activeSubSystems = new Array();
  56480. }
  56481. };
  56482. /**
  56483. * Stops the particle system.
  56484. * @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.
  56485. */
  56486. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56487. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56488. this._stopped = true;
  56489. if (stopSubEmitters) {
  56490. this._stopSubEmitters();
  56491. }
  56492. };
  56493. // animation sheet
  56494. /**
  56495. * Remove all active particles
  56496. */
  56497. ParticleSystem.prototype.reset = function () {
  56498. this._stockParticles = [];
  56499. this._particles = [];
  56500. };
  56501. /**
  56502. * @hidden (for internal use only)
  56503. */
  56504. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56505. var offset = index * this._vertexBufferSize;
  56506. this._vertexData[offset] = particle.position.x;
  56507. this._vertexData[offset + 1] = particle.position.y;
  56508. this._vertexData[offset + 2] = particle.position.z;
  56509. this._vertexData[offset + 3] = particle.color.r;
  56510. this._vertexData[offset + 4] = particle.color.g;
  56511. this._vertexData[offset + 5] = particle.color.b;
  56512. this._vertexData[offset + 6] = particle.color.a;
  56513. this._vertexData[offset + 7] = particle.angle;
  56514. this._vertexData[offset + 8] = particle.size;
  56515. this._vertexData[offset + 9] = offsetX;
  56516. this._vertexData[offset + 10] = offsetY;
  56517. };
  56518. /**
  56519. * @hidden (for internal use only)
  56520. */
  56521. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56522. if (offsetX === 0)
  56523. offsetX = this._epsilon;
  56524. else if (offsetX === 1)
  56525. offsetX = 1 - this._epsilon;
  56526. if (offsetY === 0)
  56527. offsetY = this._epsilon;
  56528. else if (offsetY === 1)
  56529. offsetY = 1 - this._epsilon;
  56530. var offset = index * this._vertexBufferSize;
  56531. this._vertexData[offset] = particle.position.x;
  56532. this._vertexData[offset + 1] = particle.position.y;
  56533. this._vertexData[offset + 2] = particle.position.z;
  56534. this._vertexData[offset + 3] = particle.color.r;
  56535. this._vertexData[offset + 4] = particle.color.g;
  56536. this._vertexData[offset + 5] = particle.color.b;
  56537. this._vertexData[offset + 6] = particle.color.a;
  56538. this._vertexData[offset + 7] = particle.angle;
  56539. this._vertexData[offset + 8] = particle.size;
  56540. this._vertexData[offset + 9] = offsetX;
  56541. this._vertexData[offset + 10] = offsetY;
  56542. this._vertexData[offset + 11] = particle.cellIndex;
  56543. };
  56544. ParticleSystem.prototype._stopSubEmitters = function () {
  56545. if (!this.activeSubSystems) {
  56546. return;
  56547. }
  56548. this.activeSubSystems.forEach(function (subSystem) {
  56549. subSystem.stop(true);
  56550. });
  56551. this.activeSubSystems = new Array();
  56552. };
  56553. ParticleSystem.prototype._removeFromRoot = function () {
  56554. if (!this._rootParticleSystem) {
  56555. return;
  56556. }
  56557. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56558. if (index !== -1) {
  56559. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56560. }
  56561. };
  56562. // end of sub system methods
  56563. ParticleSystem.prototype._update = function (newParticles) {
  56564. // Update current
  56565. this._alive = this._particles.length > 0;
  56566. this.updateFunction(this._particles);
  56567. // Add new ones
  56568. var worldMatrix;
  56569. if (this.emitter.position) {
  56570. var emitterMesh = this.emitter;
  56571. worldMatrix = emitterMesh.getWorldMatrix();
  56572. }
  56573. else {
  56574. var emitterPosition = this.emitter;
  56575. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56576. }
  56577. var particle;
  56578. for (var index = 0; index < newParticles; index++) {
  56579. if (this._particles.length === this._capacity) {
  56580. break;
  56581. }
  56582. particle = this._createParticle();
  56583. this._particles.push(particle);
  56584. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56585. if (this.startPositionFunction) {
  56586. this.startPositionFunction(worldMatrix, particle.position, particle);
  56587. }
  56588. else {
  56589. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56590. }
  56591. if (this.startDirectionFunction) {
  56592. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56593. }
  56594. else {
  56595. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56596. }
  56597. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56598. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56599. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56600. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56601. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56602. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56603. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56604. }
  56605. };
  56606. ParticleSystem.prototype._getEffect = function () {
  56607. if (this._customEffect) {
  56608. return this._customEffect;
  56609. }
  56610. ;
  56611. var defines = [];
  56612. if (this._scene.clipPlane) {
  56613. defines.push("#define CLIPPLANE");
  56614. }
  56615. if (this._isAnimationSheetEnabled) {
  56616. defines.push("#define ANIMATESHEET");
  56617. }
  56618. // Effect
  56619. var join = defines.join("\n");
  56620. if (this._cachedDefines !== join) {
  56621. this._cachedDefines = join;
  56622. var attributesNamesOrOptions;
  56623. var effectCreationOption;
  56624. if (this._isAnimationSheetEnabled) {
  56625. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56626. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56627. }
  56628. else {
  56629. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56630. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56631. }
  56632. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56633. }
  56634. return this._effect;
  56635. };
  56636. /**
  56637. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56638. */
  56639. ParticleSystem.prototype.animate = function () {
  56640. if (!this._started)
  56641. return;
  56642. var effect = this._getEffect();
  56643. // Check
  56644. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56645. return;
  56646. if (this._currentRenderId === this._scene.getRenderId()) {
  56647. return;
  56648. }
  56649. this._currentRenderId = this._scene.getRenderId();
  56650. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56651. // determine the number of particles we need to create
  56652. var newParticles;
  56653. if (this.manualEmitCount > -1) {
  56654. newParticles = this.manualEmitCount;
  56655. this._newPartsExcess = 0;
  56656. this.manualEmitCount = 0;
  56657. }
  56658. else {
  56659. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56660. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56661. }
  56662. if (this._newPartsExcess > 1.0) {
  56663. newParticles += this._newPartsExcess >> 0;
  56664. this._newPartsExcess -= this._newPartsExcess >> 0;
  56665. }
  56666. this._alive = false;
  56667. if (!this._stopped) {
  56668. this._actualFrame += this._scaledUpdateSpeed;
  56669. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56670. this.stop();
  56671. }
  56672. else {
  56673. newParticles = 0;
  56674. }
  56675. this._update(newParticles);
  56676. // Stopped?
  56677. if (this._stopped) {
  56678. if (!this._alive) {
  56679. this._started = false;
  56680. if (this.onAnimationEnd) {
  56681. this.onAnimationEnd();
  56682. }
  56683. if (this.disposeOnStop) {
  56684. this._scene._toBeDisposed.push(this);
  56685. }
  56686. }
  56687. }
  56688. // Animation sheet
  56689. if (this._isAnimationSheetEnabled) {
  56690. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56691. }
  56692. else {
  56693. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56694. }
  56695. // Update VBO
  56696. var offset = 0;
  56697. for (var index = 0; index < this._particles.length; index++) {
  56698. var particle = this._particles[index];
  56699. this._appendParticleVertexes(offset, particle);
  56700. offset += 4;
  56701. }
  56702. if (this._vertexBuffer) {
  56703. this._vertexBuffer.update(this._vertexData);
  56704. }
  56705. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56706. this.stop();
  56707. }
  56708. };
  56709. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56710. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56711. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56712. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56713. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56714. };
  56715. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56716. this._appendParticleVertex(offset++, particle, 0, 0);
  56717. this._appendParticleVertex(offset++, particle, 1, 0);
  56718. this._appendParticleVertex(offset++, particle, 1, 1);
  56719. this._appendParticleVertex(offset++, particle, 0, 1);
  56720. };
  56721. /**
  56722. * Rebuilds the particle system.
  56723. */
  56724. ParticleSystem.prototype.rebuild = function () {
  56725. this._createIndexBuffer();
  56726. if (this._vertexBuffer) {
  56727. this._vertexBuffer._rebuild();
  56728. }
  56729. };
  56730. /**
  56731. * Is this system ready to be used/rendered
  56732. * @return true if the system is ready
  56733. */
  56734. ParticleSystem.prototype.isReady = function () {
  56735. var effect = this._getEffect();
  56736. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56737. return false;
  56738. }
  56739. return true;
  56740. };
  56741. /**
  56742. * Renders the particle system in its current state.
  56743. * @returns the current number of particles
  56744. */
  56745. ParticleSystem.prototype.render = function () {
  56746. var effect = this._getEffect();
  56747. // Check
  56748. if (!this.isReady() || !this._particles.length) {
  56749. return 0;
  56750. }
  56751. var engine = this._scene.getEngine();
  56752. // Render
  56753. engine.enableEffect(effect);
  56754. engine.setState(false);
  56755. var viewMatrix = this._scene.getViewMatrix();
  56756. effect.setTexture("diffuseSampler", this.particleTexture);
  56757. effect.setMatrix("view", viewMatrix);
  56758. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56759. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56760. var baseSize = this.particleTexture.getBaseSize();
  56761. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56762. }
  56763. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56764. if (this._scene.clipPlane) {
  56765. var clipPlane = this._scene.clipPlane;
  56766. var invView = viewMatrix.clone();
  56767. invView.invert();
  56768. effect.setMatrix("invView", invView);
  56769. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56770. }
  56771. // VBOs
  56772. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56773. // Draw order
  56774. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56775. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56776. }
  56777. else {
  56778. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56779. }
  56780. if (this.forceDepthWrite) {
  56781. engine.setDepthWrite(true);
  56782. }
  56783. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56784. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56785. return this._particles.length;
  56786. };
  56787. /**
  56788. * Disposes the particle system and free the associated resources
  56789. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56790. */
  56791. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56792. if (disposeTexture === void 0) { disposeTexture = true; }
  56793. if (this._vertexBuffer) {
  56794. this._vertexBuffer.dispose();
  56795. this._vertexBuffer = null;
  56796. }
  56797. if (this._indexBuffer) {
  56798. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56799. this._indexBuffer = null;
  56800. }
  56801. if (disposeTexture && this.particleTexture) {
  56802. this.particleTexture.dispose();
  56803. this.particleTexture = null;
  56804. }
  56805. this._removeFromRoot();
  56806. // Remove from scene
  56807. var index = this._scene.particleSystems.indexOf(this);
  56808. if (index > -1) {
  56809. this._scene.particleSystems.splice(index, 1);
  56810. }
  56811. // Callback
  56812. this.onDisposeObservable.notifyObservers(this);
  56813. this.onDisposeObservable.clear();
  56814. };
  56815. /**
  56816. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56817. * @param radius The radius of the sphere to emit from
  56818. * @returns the emitter
  56819. */
  56820. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56821. if (radius === void 0) { radius = 1; }
  56822. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56823. this.particleEmitterType = particleEmitter;
  56824. return particleEmitter;
  56825. };
  56826. /**
  56827. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56828. * @param radius The radius of the sphere to emit from
  56829. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56830. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56831. * @returns the emitter
  56832. */
  56833. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56834. if (radius === void 0) { radius = 1; }
  56835. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56836. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56837. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56838. this.particleEmitterType = particleEmitter;
  56839. return particleEmitter;
  56840. };
  56841. /**
  56842. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56843. * @param radius The radius of the cone to emit from
  56844. * @param angle The base angle of the cone
  56845. * @returns the emitter
  56846. */
  56847. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56848. if (radius === void 0) { radius = 1; }
  56849. if (angle === void 0) { angle = Math.PI / 4; }
  56850. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56851. this.particleEmitterType = particleEmitter;
  56852. return particleEmitter;
  56853. };
  56854. // 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.
  56855. /**
  56856. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56857. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56858. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56859. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56860. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56861. * @returns the emitter
  56862. */
  56863. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56864. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56865. this.particleEmitterType = particleEmitter;
  56866. this.direction1 = direction1;
  56867. this.direction2 = direction2;
  56868. this.minEmitBox = minEmitBox;
  56869. this.maxEmitBox = maxEmitBox;
  56870. return particleEmitter;
  56871. };
  56872. // Clone
  56873. /**
  56874. * Clones the particle system.
  56875. * @param name The name of the cloned object
  56876. * @param newEmitter The new emitter to use
  56877. * @returns the cloned particle system
  56878. */
  56879. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56880. var custom = null;
  56881. var program = null;
  56882. if (this.customShader != null) {
  56883. program = this.customShader;
  56884. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56885. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56886. }
  56887. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56888. result.customShader = program;
  56889. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56890. if (newEmitter === undefined) {
  56891. newEmitter = this.emitter;
  56892. }
  56893. result.emitter = newEmitter;
  56894. if (this.particleTexture) {
  56895. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56896. }
  56897. if (!this.preventAutoStart) {
  56898. result.start();
  56899. }
  56900. return result;
  56901. };
  56902. /**
  56903. * Serializes the particle system to a JSON object.
  56904. * @returns the JSON object
  56905. */
  56906. ParticleSystem.prototype.serialize = function () {
  56907. var serializationObject = {};
  56908. serializationObject.name = this.name;
  56909. serializationObject.id = this.id;
  56910. // Emitter
  56911. if (this.emitter.position) {
  56912. var emitterMesh = this.emitter;
  56913. serializationObject.emitterId = emitterMesh.id;
  56914. }
  56915. else {
  56916. var emitterPosition = this.emitter;
  56917. serializationObject.emitter = emitterPosition.asArray();
  56918. }
  56919. serializationObject.capacity = this.getCapacity();
  56920. if (this.particleTexture) {
  56921. serializationObject.textureName = this.particleTexture.name;
  56922. }
  56923. // Animations
  56924. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56925. // Particle system
  56926. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56927. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56928. serializationObject.minSize = this.minSize;
  56929. serializationObject.maxSize = this.maxSize;
  56930. serializationObject.minEmitPower = this.minEmitPower;
  56931. serializationObject.maxEmitPower = this.maxEmitPower;
  56932. serializationObject.minLifeTime = this.minLifeTime;
  56933. serializationObject.maxLifeTime = this.maxLifeTime;
  56934. serializationObject.emitRate = this.emitRate;
  56935. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56936. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56937. serializationObject.gravity = this.gravity.asArray();
  56938. serializationObject.direction1 = this.direction1.asArray();
  56939. serializationObject.direction2 = this.direction2.asArray();
  56940. serializationObject.color1 = this.color1.asArray();
  56941. serializationObject.color2 = this.color2.asArray();
  56942. serializationObject.colorDead = this.colorDead.asArray();
  56943. serializationObject.updateSpeed = this.updateSpeed;
  56944. serializationObject.targetStopDuration = this.targetStopDuration;
  56945. serializationObject.textureMask = this.textureMask.asArray();
  56946. serializationObject.blendMode = this.blendMode;
  56947. serializationObject.customShader = this.customShader;
  56948. serializationObject.preventAutoStart = this.preventAutoStart;
  56949. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56950. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56951. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56952. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56953. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56954. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56955. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56956. // Emitter
  56957. if (this.particleEmitterType) {
  56958. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56959. }
  56960. return serializationObject;
  56961. };
  56962. /**
  56963. * Parses a JSON object to create a particle system.
  56964. * @param parsedParticleSystem The JSON object to parse
  56965. * @param scene The scene to create the particle system in
  56966. * @param rootUrl The root url to use to load external dependencies like texture
  56967. * @returns the Parsed particle system
  56968. */
  56969. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56970. var name = parsedParticleSystem.name;
  56971. var custom = null;
  56972. var program = null;
  56973. if (parsedParticleSystem.customShader) {
  56974. program = parsedParticleSystem.customShader;
  56975. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56976. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56977. }
  56978. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56979. particleSystem.customShader = program;
  56980. if (parsedParticleSystem.id) {
  56981. particleSystem.id = parsedParticleSystem.id;
  56982. }
  56983. // Auto start
  56984. if (parsedParticleSystem.preventAutoStart) {
  56985. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56986. }
  56987. // Texture
  56988. if (parsedParticleSystem.textureName) {
  56989. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56990. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56991. }
  56992. // Emitter
  56993. if (parsedParticleSystem.emitterId) {
  56994. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56995. }
  56996. else {
  56997. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56998. }
  56999. // Animations
  57000. if (parsedParticleSystem.animations) {
  57001. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57002. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57003. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57004. }
  57005. }
  57006. if (parsedParticleSystem.autoAnimate) {
  57007. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57008. }
  57009. // Particle system
  57010. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57011. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57012. particleSystem.minSize = parsedParticleSystem.minSize;
  57013. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57014. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57015. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57016. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57017. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57018. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57019. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57020. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57021. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57022. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57023. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57024. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57025. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57026. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57027. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57028. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57029. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57030. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57031. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57032. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57033. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57034. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57035. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57036. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57037. if (!particleSystem.preventAutoStart) {
  57038. particleSystem.start();
  57039. }
  57040. return particleSystem;
  57041. };
  57042. /**
  57043. * Source color is added to the destination color without alpha affecting the result.
  57044. */
  57045. ParticleSystem.BLENDMODE_ONEONE = 0;
  57046. /**
  57047. * Blend current color and particle color using particle’s alpha.
  57048. */
  57049. ParticleSystem.BLENDMODE_STANDARD = 1;
  57050. return ParticleSystem;
  57051. }());
  57052. BABYLON.ParticleSystem = ParticleSystem;
  57053. })(BABYLON || (BABYLON = {}));
  57054. //# sourceMappingURL=babylon.particleSystem.js.map
  57055. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57056. var BABYLON;
  57057. (function (BABYLON) {
  57058. /**
  57059. * Particle emitter emitting particles from the inside of a box.
  57060. * It emits the particles randomly between 2 given directions.
  57061. */
  57062. var BoxParticleEmitter = /** @class */ (function () {
  57063. /**
  57064. * Creates a new instance BoxParticleEmitter
  57065. */
  57066. function BoxParticleEmitter() {
  57067. /**
  57068. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57069. */
  57070. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57071. /**
  57072. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57073. */
  57074. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57075. /**
  57076. * 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.
  57077. */
  57078. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57079. /**
  57080. * 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.
  57081. */
  57082. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57083. }
  57084. /**
  57085. * Called by the particle System when the direction is computed for the created particle.
  57086. * @param emitPower is the power of the particle (speed)
  57087. * @param worldMatrix is the world matrix of the particle system
  57088. * @param directionToUpdate is the direction vector to update with the result
  57089. * @param particle is the particle we are computed the direction for
  57090. */
  57091. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57092. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57093. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57094. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57095. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57096. };
  57097. /**
  57098. * Called by the particle System when the position is computed for the created particle.
  57099. * @param worldMatrix is the world matrix of the particle system
  57100. * @param positionToUpdate is the position vector to update with the result
  57101. * @param particle is the particle we are computed the position for
  57102. */
  57103. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57104. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57105. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57106. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57107. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57108. };
  57109. /**
  57110. * Clones the current emitter and returns a copy of it
  57111. * @returns the new emitter
  57112. */
  57113. BoxParticleEmitter.prototype.clone = function () {
  57114. var newOne = new BoxParticleEmitter();
  57115. BABYLON.Tools.DeepCopy(this, newOne);
  57116. return newOne;
  57117. };
  57118. /**
  57119. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57120. * @param effect defines the update shader
  57121. */
  57122. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57123. effect.setVector3("direction1", this.direction1);
  57124. effect.setVector3("direction2", this.direction2);
  57125. effect.setVector3("minEmitBox", this.minEmitBox);
  57126. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57127. };
  57128. /**
  57129. * Returns a string to use to update the GPU particles update shader
  57130. * @returns a string containng the defines string
  57131. */
  57132. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57133. return "#define BOXEMITTER";
  57134. };
  57135. /**
  57136. * Returns the string "BoxEmitter"
  57137. * @returns a string containing the class name
  57138. */
  57139. BoxParticleEmitter.prototype.getClassName = function () {
  57140. return "BoxEmitter";
  57141. };
  57142. /**
  57143. * Serializes the particle system to a JSON object.
  57144. * @returns the JSON object
  57145. */
  57146. BoxParticleEmitter.prototype.serialize = function () {
  57147. var serializationObject = {};
  57148. serializationObject.type = this.getClassName();
  57149. serializationObject.direction1 = this.direction1.asArray();
  57150. serializationObject.direction2 = this.direction2.asArray();
  57151. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57152. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57153. return serializationObject;
  57154. };
  57155. /**
  57156. * Parse properties from a JSON object
  57157. * @param serializationObject defines the JSON object
  57158. */
  57159. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57160. this.direction1.copyFrom(serializationObject.direction1);
  57161. this.direction2.copyFrom(serializationObject.direction2);
  57162. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57163. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57164. };
  57165. return BoxParticleEmitter;
  57166. }());
  57167. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57168. })(BABYLON || (BABYLON = {}));
  57169. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57170. var BABYLON;
  57171. (function (BABYLON) {
  57172. /**
  57173. * Particle emitter emitting particles from the inside of a cone.
  57174. * It emits the particles alongside the cone volume from the base to the particle.
  57175. * The emission direction might be randomized.
  57176. */
  57177. var ConeParticleEmitter = /** @class */ (function () {
  57178. /**
  57179. * Creates a new instance ConeParticleEmitter
  57180. * @param radius the radius of the emission cone (1 by default)
  57181. * @param angles the cone base angle (PI by default)
  57182. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57183. */
  57184. function ConeParticleEmitter(radius,
  57185. /**
  57186. * The radius of the emission cone.
  57187. */
  57188. angle,
  57189. /**
  57190. * The cone base angle.
  57191. */
  57192. directionRandomizer) {
  57193. if (radius === void 0) { radius = 1; }
  57194. if (angle === void 0) { angle = Math.PI; }
  57195. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57196. this.angle = angle;
  57197. this.directionRandomizer = directionRandomizer;
  57198. this.radius = radius;
  57199. }
  57200. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57201. /**
  57202. * Gets the radius of the emission cone.
  57203. */
  57204. get: function () {
  57205. return this._radius;
  57206. },
  57207. /**
  57208. * Sets the radius of the emission cone.
  57209. */
  57210. set: function (value) {
  57211. this._radius = value;
  57212. if (this.angle !== 0) {
  57213. this._height = value / Math.tan(this.angle / 2);
  57214. }
  57215. else {
  57216. this._height = 1;
  57217. }
  57218. },
  57219. enumerable: true,
  57220. configurable: true
  57221. });
  57222. /**
  57223. * Called by the particle System when the direction is computed for the created particle.
  57224. * @param emitPower is the power of the particle (speed)
  57225. * @param worldMatrix is the world matrix of the particle system
  57226. * @param directionToUpdate is the direction vector to update with the result
  57227. * @param particle is the particle we are computed the direction for
  57228. */
  57229. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57230. if (this.angle === 0) {
  57231. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57232. }
  57233. else {
  57234. // measure the direction Vector from the emitter to the particle.
  57235. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57236. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57237. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57238. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57239. direction.x += randX;
  57240. direction.y += randY;
  57241. direction.z += randZ;
  57242. direction.normalize();
  57243. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57244. }
  57245. };
  57246. /**
  57247. * Called by the particle System when the position is computed for the created particle.
  57248. * @param worldMatrix is the world matrix of the particle system
  57249. * @param positionToUpdate is the position vector to update with the result
  57250. * @param particle is the particle we are computed the position for
  57251. */
  57252. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57253. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57254. var h = BABYLON.Scalar.RandomRange(0, 1);
  57255. // Better distribution in a cone at normal angles.
  57256. h = 1 - h * h;
  57257. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57258. radius = radius * h;
  57259. var randX = radius * Math.sin(s);
  57260. var randZ = radius * Math.cos(s);
  57261. var randY = h * this._height;
  57262. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57263. };
  57264. /**
  57265. * Clones the current emitter and returns a copy of it
  57266. * @returns the new emitter
  57267. */
  57268. ConeParticleEmitter.prototype.clone = function () {
  57269. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57270. BABYLON.Tools.DeepCopy(this, newOne);
  57271. return newOne;
  57272. };
  57273. /**
  57274. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57275. * @param effect defines the update shader
  57276. */
  57277. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57278. effect.setFloat("radius", this.radius);
  57279. effect.setFloat("coneAngle", this.angle);
  57280. effect.setFloat("height", this._height);
  57281. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57282. };
  57283. /**
  57284. * Returns a string to use to update the GPU particles update shader
  57285. * @returns a string containng the defines string
  57286. */
  57287. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57288. return "#define CONEEMITTER";
  57289. };
  57290. /**
  57291. * Returns the string "BoxEmitter"
  57292. * @returns a string containing the class name
  57293. */
  57294. ConeParticleEmitter.prototype.getClassName = function () {
  57295. return "ConeEmitter";
  57296. };
  57297. /**
  57298. * Serializes the particle system to a JSON object.
  57299. * @returns the JSON object
  57300. */
  57301. ConeParticleEmitter.prototype.serialize = function () {
  57302. var serializationObject = {};
  57303. serializationObject.type = this.getClassName();
  57304. serializationObject.radius = this.radius;
  57305. serializationObject.angle = this.angle;
  57306. serializationObject.directionRandomizer = this.directionRandomizer;
  57307. return serializationObject;
  57308. };
  57309. /**
  57310. * Parse properties from a JSON object
  57311. * @param serializationObject defines the JSON object
  57312. */
  57313. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57314. this.radius = serializationObject.radius;
  57315. this.angle = serializationObject.angle;
  57316. this.directionRandomizer = serializationObject.directionRandomizer;
  57317. };
  57318. return ConeParticleEmitter;
  57319. }());
  57320. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57321. })(BABYLON || (BABYLON = {}));
  57322. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57323. var BABYLON;
  57324. (function (BABYLON) {
  57325. /**
  57326. * Particle emitter emitting particles from the inside of a sphere.
  57327. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57328. */
  57329. var SphereParticleEmitter = /** @class */ (function () {
  57330. /**
  57331. * Creates a new instance SphereParticleEmitter
  57332. * @param radius the radius of the emission sphere (1 by default)
  57333. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57334. */
  57335. function SphereParticleEmitter(
  57336. /**
  57337. * The radius of the emission sphere.
  57338. */
  57339. radius,
  57340. /**
  57341. * How much to randomize the particle direction [0-1].
  57342. */
  57343. directionRandomizer) {
  57344. if (radius === void 0) { radius = 1; }
  57345. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57346. this.radius = radius;
  57347. this.directionRandomizer = directionRandomizer;
  57348. }
  57349. /**
  57350. * Called by the particle System when the direction is computed for the created particle.
  57351. * @param emitPower is the power of the particle (speed)
  57352. * @param worldMatrix is the world matrix of the particle system
  57353. * @param directionToUpdate is the direction vector to update with the result
  57354. * @param particle is the particle we are computed the direction for
  57355. */
  57356. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57357. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57358. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57359. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57360. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57361. direction.x += randX;
  57362. direction.y += randY;
  57363. direction.z += randZ;
  57364. direction.normalize();
  57365. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57366. };
  57367. /**
  57368. * Called by the particle System when the position is computed for the created particle.
  57369. * @param worldMatrix is the world matrix of the particle system
  57370. * @param positionToUpdate is the position vector to update with the result
  57371. * @param particle is the particle we are computed the position for
  57372. */
  57373. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57374. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57375. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57376. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57377. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57378. var randY = randRadius * Math.cos(theta);
  57379. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57380. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57381. };
  57382. /**
  57383. * Clones the current emitter and returns a copy of it
  57384. * @returns the new emitter
  57385. */
  57386. SphereParticleEmitter.prototype.clone = function () {
  57387. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57388. BABYLON.Tools.DeepCopy(this, newOne);
  57389. return newOne;
  57390. };
  57391. /**
  57392. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57393. * @param effect defines the update shader
  57394. */
  57395. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57396. effect.setFloat("radius", this.radius);
  57397. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57398. };
  57399. /**
  57400. * Returns a string to use to update the GPU particles update shader
  57401. * @returns a string containng the defines string
  57402. */
  57403. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57404. return "#define SPHEREEMITTER";
  57405. };
  57406. /**
  57407. * Returns the string "SphereParticleEmitter"
  57408. * @returns a string containing the class name
  57409. */
  57410. SphereParticleEmitter.prototype.getClassName = function () {
  57411. return "SphereParticleEmitter";
  57412. };
  57413. /**
  57414. * Serializes the particle system to a JSON object.
  57415. * @returns the JSON object
  57416. */
  57417. SphereParticleEmitter.prototype.serialize = function () {
  57418. var serializationObject = {};
  57419. serializationObject.type = this.getClassName();
  57420. serializationObject.radius = this.radius;
  57421. serializationObject.directionRandomizer = this.directionRandomizer;
  57422. return serializationObject;
  57423. };
  57424. /**
  57425. * Parse properties from a JSON object
  57426. * @param serializationObject defines the JSON object
  57427. */
  57428. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57429. this.radius = serializationObject.radius;
  57430. this.directionRandomizer = serializationObject.directionRandomizer;
  57431. };
  57432. return SphereParticleEmitter;
  57433. }());
  57434. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57435. /**
  57436. * Particle emitter emitting particles from the inside of a sphere.
  57437. * It emits the particles randomly between two vectors.
  57438. */
  57439. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57440. __extends(SphereDirectedParticleEmitter, _super);
  57441. /**
  57442. * Creates a new instance SphereDirectedParticleEmitter
  57443. * @param radius the radius of the emission sphere (1 by default)
  57444. * @param direction1 the min limit of the emission direction (up vector by default)
  57445. * @param direction2 the max limit of the emission direction (up vector by default)
  57446. */
  57447. function SphereDirectedParticleEmitter(radius,
  57448. /**
  57449. * The min limit of the emission direction.
  57450. */
  57451. direction1,
  57452. /**
  57453. * The max limit of the emission direction.
  57454. */
  57455. direction2) {
  57456. if (radius === void 0) { radius = 1; }
  57457. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57458. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57459. var _this = _super.call(this, radius) || this;
  57460. _this.direction1 = direction1;
  57461. _this.direction2 = direction2;
  57462. return _this;
  57463. }
  57464. /**
  57465. * Called by the particle System when the direction is computed for the created particle.
  57466. * @param emitPower is the power of the particle (speed)
  57467. * @param worldMatrix is the world matrix of the particle system
  57468. * @param directionToUpdate is the direction vector to update with the result
  57469. * @param particle is the particle we are computed the direction for
  57470. */
  57471. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57472. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57473. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57474. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57475. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57476. };
  57477. /**
  57478. * Clones the current emitter and returns a copy of it
  57479. * @returns the new emitter
  57480. */
  57481. SphereDirectedParticleEmitter.prototype.clone = function () {
  57482. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57483. BABYLON.Tools.DeepCopy(this, newOne);
  57484. return newOne;
  57485. };
  57486. /**
  57487. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57488. * @param effect defines the update shader
  57489. */
  57490. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57491. effect.setFloat("radius", this.radius);
  57492. effect.setVector3("direction1", this.direction1);
  57493. effect.setVector3("direction2", this.direction2);
  57494. };
  57495. /**
  57496. * Returns a string to use to update the GPU particles update shader
  57497. * @returns a string containng the defines string
  57498. */
  57499. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57500. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57501. };
  57502. /**
  57503. * Returns the string "SphereDirectedParticleEmitter"
  57504. * @returns a string containing the class name
  57505. */
  57506. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57507. return "SphereDirectedParticleEmitter";
  57508. };
  57509. /**
  57510. * Serializes the particle system to a JSON object.
  57511. * @returns the JSON object
  57512. */
  57513. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57514. var serializationObject = _super.prototype.serialize.call(this);
  57515. serializationObject.direction1 = this.direction1.asArray();
  57516. serializationObject.direction2 = this.direction2.asArray();
  57517. return serializationObject;
  57518. };
  57519. /**
  57520. * Parse properties from a JSON object
  57521. * @param serializationObject defines the JSON object
  57522. */
  57523. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57524. _super.prototype.parse.call(this, serializationObject);
  57525. this.direction1.copyFrom(serializationObject.direction1);
  57526. this.direction2.copyFrom(serializationObject.direction2);
  57527. };
  57528. return SphereDirectedParticleEmitter;
  57529. }(SphereParticleEmitter));
  57530. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57531. })(BABYLON || (BABYLON = {}));
  57532. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57533. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57534. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57535. s = arguments[i];
  57536. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57537. t[p] = s[p];
  57538. }
  57539. return t;
  57540. };
  57541. var BABYLON;
  57542. (function (BABYLON) {
  57543. /**
  57544. * This represents a GPU particle system in Babylon
  57545. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57546. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57547. */
  57548. var GPUParticleSystem = /** @class */ (function () {
  57549. /**
  57550. * Instantiates a GPU particle system.
  57551. * 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.
  57552. * @param name The name of the particle system
  57553. * @param capacity The max number of particles alive at the same time
  57554. * @param scene The scene the particle system belongs to
  57555. */
  57556. function GPUParticleSystem(name, options, scene) {
  57557. /**
  57558. * The emitter represents the Mesh or position we are attaching the particle system to.
  57559. */
  57560. this.emitter = null;
  57561. /**
  57562. * The rendering group used by the Particle system to chose when to render.
  57563. */
  57564. this.renderingGroupId = 0;
  57565. /**
  57566. * The layer mask we are rendering the particles through.
  57567. */
  57568. this.layerMask = 0x0FFFFFFF;
  57569. this._targetIndex = 0;
  57570. this._currentRenderId = -1;
  57571. this._started = false;
  57572. this._stopped = false;
  57573. this._timeDelta = 0;
  57574. this._attributesStrideSize = 16;
  57575. this._actualFrame = 0;
  57576. /**
  57577. * List of animations used by the particle system.
  57578. */
  57579. this.animations = [];
  57580. /**
  57581. * An event triggered when the system is disposed.
  57582. */
  57583. this.onDisposeObservable = new BABYLON.Observable();
  57584. /**
  57585. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57586. */
  57587. this.updateSpeed = 0.01;
  57588. /**
  57589. * The amount of time the particle system is running (depends of the overall update speed).
  57590. */
  57591. this.targetStopDuration = 0;
  57592. /**
  57593. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57594. */
  57595. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57596. /**
  57597. * Minimum life time of emitting particles.
  57598. */
  57599. this.minLifeTime = 1;
  57600. /**
  57601. * Maximum life time of emitting particles.
  57602. */
  57603. this.maxLifeTime = 1;
  57604. /**
  57605. * Minimum Size of emitting particles.
  57606. */
  57607. this.minSize = 1;
  57608. /**
  57609. * Maximum Size of emitting particles.
  57610. */
  57611. this.maxSize = 1;
  57612. /**
  57613. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57614. */
  57615. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57616. /**
  57617. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57618. */
  57619. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57620. /**
  57621. * Color the particle will have at the end of its lifetime.
  57622. */
  57623. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57624. /**
  57625. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57626. */
  57627. this.emitRate = 100;
  57628. /**
  57629. * You can use gravity if you want to give an orientation to your particles.
  57630. */
  57631. this.gravity = BABYLON.Vector3.Zero();
  57632. /**
  57633. * Minimum power of emitting particles.
  57634. */
  57635. this.minEmitPower = 1;
  57636. /**
  57637. * Maximum power of emitting particles.
  57638. */
  57639. this.maxEmitPower = 1;
  57640. /**
  57641. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57642. */
  57643. this.minAngularSpeed = 0;
  57644. /**
  57645. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57646. */
  57647. this.maxAngularSpeed = 0;
  57648. /**
  57649. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57650. * to override the particles.
  57651. */
  57652. this.forceDepthWrite = false;
  57653. this.id = name;
  57654. this.name = name;
  57655. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57656. this._engine = this._scene.getEngine();
  57657. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57658. this._capacity = fullOptions.capacity;
  57659. this._activeCount = fullOptions.capacity;
  57660. this._currentActiveCount = 0;
  57661. this._scene.particleSystems.push(this);
  57662. this._updateEffectOptions = {
  57663. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57664. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57665. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57666. "angleRange"],
  57667. uniformBuffersNames: [],
  57668. samplers: ["randomSampler"],
  57669. defines: "",
  57670. fallbacks: null,
  57671. onCompiled: null,
  57672. onError: null,
  57673. indexParameters: null,
  57674. maxSimultaneousLights: 0,
  57675. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57676. };
  57677. // Random data
  57678. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57679. var d = [];
  57680. for (var i = 0; i < maxTextureSize; ++i) {
  57681. d.push(Math.random());
  57682. d.push(Math.random());
  57683. d.push(Math.random());
  57684. d.push(Math.random());
  57685. }
  57686. 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);
  57687. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57688. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57689. this._randomTextureSize = maxTextureSize;
  57690. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57691. }
  57692. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57693. /**
  57694. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57695. */
  57696. get: function () {
  57697. if (!BABYLON.Engine.LastCreatedEngine) {
  57698. return false;
  57699. }
  57700. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57701. },
  57702. enumerable: true,
  57703. configurable: true
  57704. });
  57705. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57706. /**
  57707. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57708. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57709. */
  57710. get: function () {
  57711. if (this.particleEmitterType.direction1) {
  57712. return this.particleEmitterType.direction1;
  57713. }
  57714. return BABYLON.Vector3.Zero();
  57715. },
  57716. set: function (value) {
  57717. if (this.particleEmitterType.direction1) {
  57718. this.particleEmitterType.direction1 = value;
  57719. }
  57720. },
  57721. enumerable: true,
  57722. configurable: true
  57723. });
  57724. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57725. /**
  57726. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57727. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57728. */
  57729. get: function () {
  57730. if (this.particleEmitterType.direction2) {
  57731. return this.particleEmitterType.direction2;
  57732. }
  57733. return BABYLON.Vector3.Zero();
  57734. },
  57735. set: function (value) {
  57736. if (this.particleEmitterType.direction2) {
  57737. this.particleEmitterType.direction2 = value;
  57738. }
  57739. },
  57740. enumerable: true,
  57741. configurable: true
  57742. });
  57743. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57744. /**
  57745. * 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.
  57746. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57747. */
  57748. get: function () {
  57749. if (this.particleEmitterType.minEmitBox) {
  57750. return this.particleEmitterType.minEmitBox;
  57751. }
  57752. return BABYLON.Vector3.Zero();
  57753. },
  57754. set: function (value) {
  57755. if (this.particleEmitterType.minEmitBox) {
  57756. this.particleEmitterType.minEmitBox = value;
  57757. }
  57758. },
  57759. enumerable: true,
  57760. configurable: true
  57761. });
  57762. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57763. /**
  57764. * 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.
  57765. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57766. */
  57767. get: function () {
  57768. if (this.particleEmitterType.maxEmitBox) {
  57769. return this.particleEmitterType.maxEmitBox;
  57770. }
  57771. return BABYLON.Vector3.Zero();
  57772. },
  57773. set: function (value) {
  57774. if (this.particleEmitterType.maxEmitBox) {
  57775. this.particleEmitterType.maxEmitBox = value;
  57776. }
  57777. },
  57778. enumerable: true,
  57779. configurable: true
  57780. });
  57781. /**
  57782. * Gets the maximum number of particles active at the same time.
  57783. * @returns The max number of active particles.
  57784. */
  57785. GPUParticleSystem.prototype.getCapacity = function () {
  57786. return this._capacity;
  57787. };
  57788. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57789. /**
  57790. * Gets or set the number of active particles
  57791. */
  57792. get: function () {
  57793. return this._activeCount;
  57794. },
  57795. set: function (value) {
  57796. this._activeCount = Math.min(value, this._capacity);
  57797. },
  57798. enumerable: true,
  57799. configurable: true
  57800. });
  57801. /**
  57802. * Is this system ready to be used/rendered
  57803. * @return true if the system is ready
  57804. */
  57805. GPUParticleSystem.prototype.isReady = function () {
  57806. if (!this._updateEffect) {
  57807. this._recreateUpdateEffect();
  57808. this._recreateRenderEffect();
  57809. return false;
  57810. }
  57811. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57812. return false;
  57813. }
  57814. return true;
  57815. };
  57816. /**
  57817. * Gets Wether the system has been started.
  57818. * @returns True if it has been started, otherwise false.
  57819. */
  57820. GPUParticleSystem.prototype.isStarted = function () {
  57821. return this._started;
  57822. };
  57823. /**
  57824. * Starts the particle system and begins to emit.
  57825. */
  57826. GPUParticleSystem.prototype.start = function () {
  57827. this._started = true;
  57828. this._stopped = false;
  57829. };
  57830. /**
  57831. * Stops the particle system.
  57832. */
  57833. GPUParticleSystem.prototype.stop = function () {
  57834. this._stopped = true;
  57835. };
  57836. /**
  57837. * Remove all active particles
  57838. */
  57839. GPUParticleSystem.prototype.reset = function () {
  57840. this._releaseBuffers();
  57841. this._releaseVAOs();
  57842. this._currentActiveCount = 0;
  57843. this._targetIndex = 0;
  57844. };
  57845. /**
  57846. * Returns the string "GPUParticleSystem"
  57847. * @returns a string containing the class name
  57848. */
  57849. GPUParticleSystem.prototype.getClassName = function () {
  57850. return "GPUParticleSystem";
  57851. };
  57852. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57853. var updateVertexBuffers = {};
  57854. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57855. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57856. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57857. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57858. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57859. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57860. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57861. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57862. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57863. this._engine.bindArrayBuffer(null);
  57864. return vao;
  57865. };
  57866. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57867. var renderVertexBuffers = {};
  57868. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57869. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57870. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57871. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57872. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57873. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57874. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57875. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57876. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57877. this._engine.bindArrayBuffer(null);
  57878. return vao;
  57879. };
  57880. GPUParticleSystem.prototype._initialize = function (force) {
  57881. if (force === void 0) { force = false; }
  57882. if (this._buffer0 && !force) {
  57883. return;
  57884. }
  57885. var engine = this._scene.getEngine();
  57886. var data = new Array();
  57887. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57888. // position
  57889. data.push(0.0);
  57890. data.push(0.0);
  57891. data.push(0.0);
  57892. // Age and life
  57893. data.push(0.0); // create the particle as a dead one to create a new one at start
  57894. data.push(0.0);
  57895. // Seed
  57896. data.push(Math.random());
  57897. // Size
  57898. data.push(0.0);
  57899. // color
  57900. data.push(0.0);
  57901. data.push(0.0);
  57902. data.push(0.0);
  57903. data.push(0.0);
  57904. // direction
  57905. data.push(0.0);
  57906. data.push(0.0);
  57907. data.push(0.0);
  57908. // angle
  57909. data.push(0.0);
  57910. data.push(0.0);
  57911. }
  57912. // Sprite data
  57913. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57914. -0.5, 0.5, 0, 1,
  57915. -0.5, -0.5, 0, 0,
  57916. 0.5, -0.5, 1, 0]);
  57917. // Buffers
  57918. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57919. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57920. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57921. // Update VAO
  57922. this._updateVAO = [];
  57923. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57924. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57925. // Render VAO
  57926. this._renderVAO = [];
  57927. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57928. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57929. // Links
  57930. this._sourceBuffer = this._buffer0;
  57931. this._targetBuffer = this._buffer1;
  57932. };
  57933. /** @hidden */
  57934. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57935. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57936. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57937. return;
  57938. }
  57939. this._updateEffectOptions.defines = defines;
  57940. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57941. };
  57942. /** @hidden */
  57943. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57944. var defines = "";
  57945. if (this._scene.clipPlane) {
  57946. defines = "\n#define CLIPPLANE";
  57947. }
  57948. if (this._renderEffect && this._renderEffect.defines === defines) {
  57949. return;
  57950. }
  57951. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57952. };
  57953. /**
  57954. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57955. */
  57956. GPUParticleSystem.prototype.animate = function () {
  57957. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57958. this._actualFrame += this._timeDelta;
  57959. if (!this._stopped) {
  57960. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57961. this.stop();
  57962. }
  57963. }
  57964. };
  57965. /**
  57966. * Renders the particle system in its current state.
  57967. * @returns the current number of particles
  57968. */
  57969. GPUParticleSystem.prototype.render = function () {
  57970. if (!this._started) {
  57971. return 0;
  57972. }
  57973. this._recreateUpdateEffect();
  57974. this._recreateRenderEffect();
  57975. if (!this.isReady()) {
  57976. return 0;
  57977. }
  57978. if (this._currentRenderId === this._scene.getRenderId()) {
  57979. return 0;
  57980. }
  57981. this._currentRenderId = this._scene.getRenderId();
  57982. // Get everything ready to render
  57983. this._initialize();
  57984. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57985. // Enable update effect
  57986. this._engine.enableEffect(this._updateEffect);
  57987. this._engine.setState(false);
  57988. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57989. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57990. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57991. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57992. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57993. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57994. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57995. this._updateEffect.setDirectColor4("color1", this.color1);
  57996. this._updateEffect.setDirectColor4("color2", this.color2);
  57997. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57998. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57999. this._updateEffect.setVector3("gravity", this.gravity);
  58000. if (this.particleEmitterType) {
  58001. this.particleEmitterType.applyToShader(this._updateEffect);
  58002. }
  58003. var emitterWM;
  58004. if (this.emitter.position) {
  58005. var emitterMesh = this.emitter;
  58006. emitterWM = emitterMesh.getWorldMatrix();
  58007. }
  58008. else {
  58009. var emitterPosition = this.emitter;
  58010. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58011. }
  58012. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58013. // Bind source VAO
  58014. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58015. // Update
  58016. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58017. this._engine.setRasterizerState(false);
  58018. this._engine.beginTransformFeedback();
  58019. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58020. this._engine.endTransformFeedback();
  58021. this._engine.setRasterizerState(true);
  58022. this._engine.bindTransformFeedbackBuffer(null);
  58023. // Enable render effect
  58024. this._engine.enableEffect(this._renderEffect);
  58025. var viewMatrix = this._scene.getViewMatrix();
  58026. this._renderEffect.setMatrix("view", viewMatrix);
  58027. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58028. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58029. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58030. if (this._scene.clipPlane) {
  58031. var clipPlane = this._scene.clipPlane;
  58032. var invView = viewMatrix.clone();
  58033. invView.invert();
  58034. this._renderEffect.setMatrix("invView", invView);
  58035. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58036. }
  58037. // Draw order
  58038. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58039. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58040. }
  58041. else {
  58042. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58043. }
  58044. if (this.forceDepthWrite) {
  58045. this._engine.setDepthWrite(true);
  58046. }
  58047. // Bind source VAO
  58048. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58049. // Render
  58050. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58051. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58052. // Switch VAOs
  58053. this._targetIndex++;
  58054. if (this._targetIndex === 2) {
  58055. this._targetIndex = 0;
  58056. }
  58057. // Switch buffers
  58058. var tmpBuffer = this._sourceBuffer;
  58059. this._sourceBuffer = this._targetBuffer;
  58060. this._targetBuffer = tmpBuffer;
  58061. return this._currentActiveCount;
  58062. };
  58063. /**
  58064. * Rebuilds the particle system
  58065. */
  58066. GPUParticleSystem.prototype.rebuild = function () {
  58067. this._initialize(true);
  58068. };
  58069. GPUParticleSystem.prototype._releaseBuffers = function () {
  58070. if (this._buffer0) {
  58071. this._buffer0.dispose();
  58072. this._buffer0 = null;
  58073. }
  58074. if (this._buffer1) {
  58075. this._buffer1.dispose();
  58076. this._buffer1 = null;
  58077. }
  58078. if (this._spriteBuffer) {
  58079. this._spriteBuffer.dispose();
  58080. this._spriteBuffer = null;
  58081. }
  58082. };
  58083. GPUParticleSystem.prototype._releaseVAOs = function () {
  58084. if (!this._updateVAO) {
  58085. return;
  58086. }
  58087. for (var index = 0; index < this._updateVAO.length; index++) {
  58088. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58089. }
  58090. this._updateVAO = [];
  58091. for (var index = 0; index < this._renderVAO.length; index++) {
  58092. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58093. }
  58094. this._renderVAO = [];
  58095. };
  58096. /**
  58097. * Disposes the particle system and free the associated resources
  58098. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58099. */
  58100. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58101. if (disposeTexture === void 0) { disposeTexture = true; }
  58102. var index = this._scene.particleSystems.indexOf(this);
  58103. if (index > -1) {
  58104. this._scene.particleSystems.splice(index, 1);
  58105. }
  58106. this._releaseBuffers();
  58107. this._releaseVAOs();
  58108. if (this._randomTexture) {
  58109. this._randomTexture.dispose();
  58110. this._randomTexture = null;
  58111. }
  58112. if (disposeTexture && this.particleTexture) {
  58113. this.particleTexture.dispose();
  58114. this.particleTexture = null;
  58115. }
  58116. // Callback
  58117. this.onDisposeObservable.notifyObservers(this);
  58118. this.onDisposeObservable.clear();
  58119. };
  58120. /**
  58121. * Clones the particle system.
  58122. * @param name The name of the cloned object
  58123. * @param newEmitter The new emitter to use
  58124. * @returns the cloned particle system
  58125. */
  58126. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58127. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58128. BABYLON.Tools.DeepCopy(this, result);
  58129. if (newEmitter === undefined) {
  58130. newEmitter = this.emitter;
  58131. }
  58132. result.emitter = newEmitter;
  58133. if (this.particleTexture) {
  58134. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58135. }
  58136. return result;
  58137. };
  58138. /**
  58139. * Serializes the particle system to a JSON object.
  58140. * @returns the JSON object
  58141. */
  58142. GPUParticleSystem.prototype.serialize = function () {
  58143. var serializationObject = {};
  58144. serializationObject.name = this.name;
  58145. serializationObject.id = this.id;
  58146. // Emitter
  58147. if (this.emitter.position) {
  58148. var emitterMesh = this.emitter;
  58149. serializationObject.emitterId = emitterMesh.id;
  58150. }
  58151. else {
  58152. var emitterPosition = this.emitter;
  58153. serializationObject.emitter = emitterPosition.asArray();
  58154. }
  58155. serializationObject.capacity = this.getCapacity();
  58156. if (this.particleTexture) {
  58157. serializationObject.textureName = this.particleTexture.name;
  58158. }
  58159. // Animations
  58160. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58161. // Particle system
  58162. serializationObject.activeParticleCount = this.activeParticleCount;
  58163. serializationObject.randomTextureSize = this._randomTextureSize;
  58164. serializationObject.minSize = this.minSize;
  58165. serializationObject.maxSize = this.maxSize;
  58166. serializationObject.minEmitPower = this.minEmitPower;
  58167. serializationObject.maxEmitPower = this.maxEmitPower;
  58168. serializationObject.minLifeTime = this.minLifeTime;
  58169. serializationObject.maxLifeTime = this.maxLifeTime;
  58170. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58171. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58172. serializationObject.emitRate = this.emitRate;
  58173. serializationObject.gravity = this.gravity.asArray();
  58174. serializationObject.color1 = this.color1.asArray();
  58175. serializationObject.color2 = this.color2.asArray();
  58176. serializationObject.colorDead = this.colorDead.asArray();
  58177. serializationObject.updateSpeed = this.updateSpeed;
  58178. serializationObject.targetStopDuration = this.targetStopDuration;
  58179. serializationObject.blendMode = this.blendMode;
  58180. // Emitter
  58181. if (this.particleEmitterType) {
  58182. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58183. }
  58184. return serializationObject;
  58185. };
  58186. /**
  58187. * Parses a JSON object to create a GPU particle system.
  58188. * @param parsedParticleSystem The JSON object to parse
  58189. * @param scene The scene to create the particle system in
  58190. * @param rootUrl The root url to use to load external dependencies like texture
  58191. * @returns the parsed GPU particle system
  58192. */
  58193. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58194. var name = parsedParticleSystem.name;
  58195. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58196. if (parsedParticleSystem.id) {
  58197. particleSystem.id = parsedParticleSystem.id;
  58198. }
  58199. // Texture
  58200. if (parsedParticleSystem.textureName) {
  58201. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58202. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58203. }
  58204. // Emitter
  58205. if (parsedParticleSystem.emitterId) {
  58206. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58207. }
  58208. else {
  58209. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58210. }
  58211. // Animations
  58212. if (parsedParticleSystem.animations) {
  58213. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58214. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58215. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58216. }
  58217. }
  58218. // Particle system
  58219. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58220. particleSystem.minSize = parsedParticleSystem.minSize;
  58221. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58222. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58223. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58224. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58225. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58226. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58227. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58228. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58229. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58230. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58231. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58232. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58233. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58234. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58235. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58236. // Emitter
  58237. if (parsedParticleSystem.particleEmitterType) {
  58238. var emitterType = void 0;
  58239. switch (parsedParticleSystem.particleEmitterType.type) {
  58240. case "SphereEmitter":
  58241. emitterType = new BABYLON.SphereParticleEmitter();
  58242. break;
  58243. case "SphereDirectedParticleEmitter":
  58244. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58245. break;
  58246. case "ConeEmitter":
  58247. emitterType = new BABYLON.ConeParticleEmitter();
  58248. break;
  58249. case "BoxEmitter":
  58250. default:
  58251. emitterType = new BABYLON.BoxParticleEmitter();
  58252. break;
  58253. }
  58254. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58255. particleSystem.particleEmitterType = emitterType;
  58256. }
  58257. return particleSystem;
  58258. };
  58259. return GPUParticleSystem;
  58260. }());
  58261. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58262. })(BABYLON || (BABYLON = {}));
  58263. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58264. var BABYLON;
  58265. (function (BABYLON) {
  58266. /**
  58267. * Represents one particle of a solid particle system.
  58268. */
  58269. var SolidParticle = /** @class */ (function () {
  58270. /**
  58271. * Creates a Solid Particle object.
  58272. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58273. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58274. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58275. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58276. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58277. * @param shapeId (integer) is the model shape identifier in the SPS.
  58278. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58279. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58280. */
  58281. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58282. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58283. /**
  58284. * particle global index
  58285. */
  58286. this.idx = 0;
  58287. /**
  58288. * The color of the particle
  58289. */
  58290. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58291. /**
  58292. * The world space position of the particle.
  58293. */
  58294. this.position = BABYLON.Vector3.Zero();
  58295. /**
  58296. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58297. */
  58298. this.rotation = BABYLON.Vector3.Zero();
  58299. /**
  58300. * The scaling of the particle.
  58301. */
  58302. this.scaling = BABYLON.Vector3.One();
  58303. /**
  58304. * The uvs of the particle.
  58305. */
  58306. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58307. /**
  58308. * The current speed of the particle.
  58309. */
  58310. this.velocity = BABYLON.Vector3.Zero();
  58311. /**
  58312. * The pivot point in the particle local space.
  58313. */
  58314. this.pivot = BABYLON.Vector3.Zero();
  58315. /**
  58316. * Must the particle be translated from its pivot point in its local space ?
  58317. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58318. * Default : false
  58319. */
  58320. this.translateFromPivot = false;
  58321. /**
  58322. * Is the particle active or not ?
  58323. */
  58324. this.alive = true;
  58325. /**
  58326. * Is the particle visible or not ?
  58327. */
  58328. this.isVisible = true;
  58329. /**
  58330. * Index of this particle in the global "positions" array (Internal use)
  58331. */
  58332. this._pos = 0;
  58333. /**
  58334. * Index of this particle in the global "indices" array (Internal use)
  58335. */
  58336. this._ind = 0;
  58337. /**
  58338. * ModelShape id of this particle
  58339. */
  58340. this.shapeId = 0;
  58341. /**
  58342. * Index of the particle in its shape id (Internal use)
  58343. */
  58344. this.idxInShape = 0;
  58345. /**
  58346. * Still set as invisible in order to skip useless computations (Internal use)
  58347. */
  58348. this._stillInvisible = false;
  58349. /**
  58350. * Last computed particle rotation matrix
  58351. */
  58352. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58353. /**
  58354. * Parent particle Id, if any.
  58355. * Default null.
  58356. */
  58357. this.parentId = null;
  58358. /**
  58359. * Internal global position in the SPS.
  58360. */
  58361. this._globalPosition = BABYLON.Vector3.Zero();
  58362. this.idx = particleIndex;
  58363. this._pos = positionIndex;
  58364. this._ind = indiceIndex;
  58365. this._model = model;
  58366. this.shapeId = shapeId;
  58367. this.idxInShape = idxInShape;
  58368. this._sps = sps;
  58369. if (modelBoundingInfo) {
  58370. this._modelBoundingInfo = modelBoundingInfo;
  58371. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58372. }
  58373. }
  58374. Object.defineProperty(SolidParticle.prototype, "scale", {
  58375. /**
  58376. * Legacy support, changed scale to scaling
  58377. */
  58378. get: function () {
  58379. return this.scaling;
  58380. },
  58381. /**
  58382. * Legacy support, changed scale to scaling
  58383. */
  58384. set: function (scale) {
  58385. this.scaling = scale;
  58386. },
  58387. enumerable: true,
  58388. configurable: true
  58389. });
  58390. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58391. /**
  58392. * Legacy support, changed quaternion to rotationQuaternion
  58393. */
  58394. get: function () {
  58395. return this.rotationQuaternion;
  58396. },
  58397. /**
  58398. * Legacy support, changed quaternion to rotationQuaternion
  58399. */
  58400. set: function (q) {
  58401. this.rotationQuaternion = q;
  58402. },
  58403. enumerable: true,
  58404. configurable: true
  58405. });
  58406. /**
  58407. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58408. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58409. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58410. * @returns true if it intersects
  58411. */
  58412. SolidParticle.prototype.intersectsMesh = function (target) {
  58413. if (!this._boundingInfo || !target._boundingInfo) {
  58414. return false;
  58415. }
  58416. if (this._sps._bSphereOnly) {
  58417. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58418. }
  58419. return this._boundingInfo.intersects(target._boundingInfo, false);
  58420. };
  58421. return SolidParticle;
  58422. }());
  58423. BABYLON.SolidParticle = SolidParticle;
  58424. /**
  58425. * Represents the shape of the model used by one particle of a solid particle system.
  58426. * SPS internal tool, don't use it manually.
  58427. */
  58428. var ModelShape = /** @class */ (function () {
  58429. /**
  58430. * 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.
  58431. * SPS internal tool, don't use it manually.
  58432. * @hidden
  58433. */
  58434. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58435. /**
  58436. * length of the shape in the model indices array (internal use)
  58437. */
  58438. this._indicesLength = 0;
  58439. this.shapeID = id;
  58440. this._shape = shape;
  58441. this._indicesLength = indicesLength;
  58442. this._shapeUV = shapeUV;
  58443. this._positionFunction = posFunction;
  58444. this._vertexFunction = vtxFunction;
  58445. }
  58446. return ModelShape;
  58447. }());
  58448. BABYLON.ModelShape = ModelShape;
  58449. /**
  58450. * Represents a Depth Sorted Particle in the solid particle system.
  58451. */
  58452. var DepthSortedParticle = /** @class */ (function () {
  58453. function DepthSortedParticle() {
  58454. /**
  58455. * Index of the particle in the "indices" array
  58456. */
  58457. this.ind = 0;
  58458. /**
  58459. * Length of the particle shape in the "indices" array
  58460. */
  58461. this.indicesLength = 0;
  58462. /**
  58463. * Squared distance from the particle to the camera
  58464. */
  58465. this.sqDistance = 0.0;
  58466. }
  58467. return DepthSortedParticle;
  58468. }());
  58469. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58470. })(BABYLON || (BABYLON = {}));
  58471. //# sourceMappingURL=babylon.solidParticle.js.map
  58472. var BABYLON;
  58473. (function (BABYLON) {
  58474. /**
  58475. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58476. *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.
  58477. * The SPS is also a particle system. It provides some methods to manage the particles.
  58478. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58479. *
  58480. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58481. */
  58482. var SolidParticleSystem = /** @class */ (function () {
  58483. /**
  58484. * Creates a SPS (Solid Particle System) object.
  58485. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58486. * @param scene (Scene) is the scene in which the SPS is added.
  58487. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58488. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58489. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58490. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58491. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58492. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58493. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58494. */
  58495. function SolidParticleSystem(name, scene, options) {
  58496. /**
  58497. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58498. * Example : var p = SPS.particles[i];
  58499. */
  58500. this.particles = new Array();
  58501. /**
  58502. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58503. */
  58504. this.nbParticles = 0;
  58505. /**
  58506. * If the particles must ever face the camera (default false). Useful for planar particles.
  58507. */
  58508. this.billboard = false;
  58509. /**
  58510. * Recompute normals when adding a shape
  58511. */
  58512. this.recomputeNormals = true;
  58513. /**
  58514. * This a counter ofr your own usage. It's not set by any SPS functions.
  58515. */
  58516. this.counter = 0;
  58517. /**
  58518. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58519. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58520. */
  58521. this.vars = {};
  58522. /**
  58523. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58524. */
  58525. this._bSphereOnly = false;
  58526. /**
  58527. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58528. */
  58529. this._bSphereRadiusFactor = 1.0;
  58530. this._positions = new Array();
  58531. this._indices = new Array();
  58532. this._normals = new Array();
  58533. this._colors = new Array();
  58534. this._uvs = new Array();
  58535. this._index = 0; // indices index
  58536. this._updatable = true;
  58537. this._pickable = false;
  58538. this._isVisibilityBoxLocked = false;
  58539. this._alwaysVisible = false;
  58540. this._depthSort = false;
  58541. this._shapeCounter = 0;
  58542. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58543. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58544. this._computeParticleColor = true;
  58545. this._computeParticleTexture = true;
  58546. this._computeParticleRotation = true;
  58547. this._computeParticleVertex = false;
  58548. this._computeBoundingBox = false;
  58549. this._depthSortParticles = true;
  58550. this._cam_axisZ = BABYLON.Vector3.Zero();
  58551. this._cam_axisY = BABYLON.Vector3.Zero();
  58552. this._cam_axisX = BABYLON.Vector3.Zero();
  58553. this._axisZ = BABYLON.Axis.Z;
  58554. this._camDir = BABYLON.Vector3.Zero();
  58555. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58556. this._rotMatrix = new BABYLON.Matrix();
  58557. this._invertMatrix = new BABYLON.Matrix();
  58558. this._rotated = BABYLON.Vector3.Zero();
  58559. this._quaternion = new BABYLON.Quaternion();
  58560. this._vertex = BABYLON.Vector3.Zero();
  58561. this._normal = BABYLON.Vector3.Zero();
  58562. this._yaw = 0.0;
  58563. this._pitch = 0.0;
  58564. this._roll = 0.0;
  58565. this._halfroll = 0.0;
  58566. this._halfpitch = 0.0;
  58567. this._halfyaw = 0.0;
  58568. this._sinRoll = 0.0;
  58569. this._cosRoll = 0.0;
  58570. this._sinPitch = 0.0;
  58571. this._cosPitch = 0.0;
  58572. this._sinYaw = 0.0;
  58573. this._cosYaw = 0.0;
  58574. this._mustUnrotateFixedNormals = false;
  58575. this._minimum = BABYLON.Vector3.Zero();
  58576. this._maximum = BABYLON.Vector3.Zero();
  58577. this._minBbox = BABYLON.Vector3.Zero();
  58578. this._maxBbox = BABYLON.Vector3.Zero();
  58579. this._particlesIntersect = false;
  58580. this._depthSortFunction = function (p1, p2) {
  58581. return (p2.sqDistance - p1.sqDistance);
  58582. };
  58583. this._needs32Bits = false;
  58584. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58585. this._scaledPivot = BABYLON.Vector3.Zero();
  58586. this._particleHasParent = false;
  58587. this.name = name;
  58588. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58589. this._camera = scene.activeCamera;
  58590. this._pickable = options ? options.isPickable : false;
  58591. this._depthSort = options ? options.enableDepthSort : false;
  58592. this._particlesIntersect = options ? options.particleIntersection : false;
  58593. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58594. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58595. if (options && options.updatable) {
  58596. this._updatable = options.updatable;
  58597. }
  58598. else {
  58599. this._updatable = true;
  58600. }
  58601. if (this._pickable) {
  58602. this.pickedParticles = [];
  58603. }
  58604. if (this._depthSort) {
  58605. this.depthSortedParticles = [];
  58606. }
  58607. }
  58608. /**
  58609. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58610. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58611. * @returns the created mesh
  58612. */
  58613. SolidParticleSystem.prototype.buildMesh = function () {
  58614. if (this.nbParticles === 0) {
  58615. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58616. this.addShape(triangle, 1);
  58617. triangle.dispose();
  58618. }
  58619. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58620. this._positions32 = new Float32Array(this._positions);
  58621. this._uvs32 = new Float32Array(this._uvs);
  58622. this._colors32 = new Float32Array(this._colors);
  58623. if (this.recomputeNormals) {
  58624. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58625. }
  58626. this._normals32 = new Float32Array(this._normals);
  58627. this._fixedNormal32 = new Float32Array(this._normals);
  58628. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58629. this._unrotateFixedNormals();
  58630. }
  58631. var vertexData = new BABYLON.VertexData();
  58632. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58633. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58634. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58635. if (this._uvs32.length > 0) {
  58636. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58637. }
  58638. if (this._colors32.length > 0) {
  58639. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58640. }
  58641. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58642. vertexData.applyToMesh(mesh, this._updatable);
  58643. this.mesh = mesh;
  58644. this.mesh.isPickable = this._pickable;
  58645. // free memory
  58646. if (!this._depthSort) {
  58647. this._indices = null;
  58648. }
  58649. this._positions = null;
  58650. this._normals = null;
  58651. this._uvs = null;
  58652. this._colors = null;
  58653. if (!this._updatable) {
  58654. this.particles.length = 0;
  58655. }
  58656. return mesh;
  58657. };
  58658. /**
  58659. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58660. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58661. * Thus the particles generated from `digest()` have their property `position` set yet.
  58662. * @param mesh ( Mesh ) is the mesh to be digested
  58663. * @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
  58664. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58665. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58666. * @returns the current SPS
  58667. */
  58668. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58669. var size = (options && options.facetNb) || 1;
  58670. var number = (options && options.number) || 0;
  58671. var delta = (options && options.delta) || 0;
  58672. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58673. var meshInd = mesh.getIndices();
  58674. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58675. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58676. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58677. var f = 0; // facet counter
  58678. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58679. // compute size from number
  58680. if (number) {
  58681. number = (number > totalFacets) ? totalFacets : number;
  58682. size = Math.round(totalFacets / number);
  58683. delta = 0;
  58684. }
  58685. else {
  58686. size = (size > totalFacets) ? totalFacets : size;
  58687. }
  58688. var facetPos = []; // submesh positions
  58689. var facetInd = []; // submesh indices
  58690. var facetUV = []; // submesh UV
  58691. var facetCol = []; // submesh colors
  58692. var barycenter = BABYLON.Vector3.Zero();
  58693. var sizeO = size;
  58694. while (f < totalFacets) {
  58695. size = sizeO + Math.floor((1 + delta) * Math.random());
  58696. if (f > totalFacets - size) {
  58697. size = totalFacets - f;
  58698. }
  58699. // reset temp arrays
  58700. facetPos.length = 0;
  58701. facetInd.length = 0;
  58702. facetUV.length = 0;
  58703. facetCol.length = 0;
  58704. // iterate over "size" facets
  58705. var fi = 0;
  58706. for (var j = f * 3; j < (f + size) * 3; j++) {
  58707. facetInd.push(fi);
  58708. var i = meshInd[j];
  58709. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58710. if (meshUV) {
  58711. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58712. }
  58713. if (meshCol) {
  58714. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58715. }
  58716. fi++;
  58717. }
  58718. // create a model shape for each single particle
  58719. var idx = this.nbParticles;
  58720. var shape = this._posToShape(facetPos);
  58721. var shapeUV = this._uvsToShapeUV(facetUV);
  58722. // compute the barycenter of the shape
  58723. var v;
  58724. for (v = 0; v < shape.length; v++) {
  58725. barycenter.addInPlace(shape[v]);
  58726. }
  58727. barycenter.scaleInPlace(1 / shape.length);
  58728. // shift the shape from its barycenter to the origin
  58729. for (v = 0; v < shape.length; v++) {
  58730. shape[v].subtractInPlace(barycenter);
  58731. }
  58732. var bInfo;
  58733. if (this._particlesIntersect) {
  58734. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58735. }
  58736. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58737. // add the particle in the SPS
  58738. var currentPos = this._positions.length;
  58739. var currentInd = this._indices.length;
  58740. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58741. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58742. // initialize the particle position
  58743. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58744. this._index += shape.length;
  58745. idx++;
  58746. this.nbParticles++;
  58747. this._shapeCounter++;
  58748. f += size;
  58749. }
  58750. return this;
  58751. };
  58752. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58753. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58754. var index = 0;
  58755. var idx = 0;
  58756. for (var p = 0; p < this.particles.length; p++) {
  58757. this._particle = this.particles[p];
  58758. this._shape = this._particle._model._shape;
  58759. if (this._particle.rotationQuaternion) {
  58760. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58761. }
  58762. else {
  58763. this._yaw = this._particle.rotation.y;
  58764. this._pitch = this._particle.rotation.x;
  58765. this._roll = this._particle.rotation.z;
  58766. this._quaternionRotationYPR();
  58767. }
  58768. this._quaternionToRotationMatrix();
  58769. this._rotMatrix.invertToRef(this._invertMatrix);
  58770. for (var pt = 0; pt < this._shape.length; pt++) {
  58771. idx = index + pt * 3;
  58772. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58773. this._fixedNormal32[idx] = this._normal.x;
  58774. this._fixedNormal32[idx + 1] = this._normal.y;
  58775. this._fixedNormal32[idx + 2] = this._normal.z;
  58776. }
  58777. index = idx + 3;
  58778. }
  58779. };
  58780. //reset copy
  58781. SolidParticleSystem.prototype._resetCopy = function () {
  58782. this._copy.position.x = 0;
  58783. this._copy.position.y = 0;
  58784. this._copy.position.z = 0;
  58785. this._copy.rotation.x = 0;
  58786. this._copy.rotation.y = 0;
  58787. this._copy.rotation.z = 0;
  58788. this._copy.rotationQuaternion = null;
  58789. this._copy.scaling.x = 1.0;
  58790. this._copy.scaling.y = 1.0;
  58791. this._copy.scaling.z = 1.0;
  58792. this._copy.uvs.x = 0;
  58793. this._copy.uvs.y = 0;
  58794. this._copy.uvs.z = 1.0;
  58795. this._copy.uvs.w = 1.0;
  58796. this._copy.color = null;
  58797. this._copy.translateFromPivot = false;
  58798. };
  58799. // _meshBuilder : inserts the shape model in the global SPS mesh
  58800. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58801. var i;
  58802. var u = 0;
  58803. var c = 0;
  58804. var n = 0;
  58805. this._resetCopy();
  58806. if (options && options.positionFunction) { // call to custom positionFunction
  58807. options.positionFunction(this._copy, idx, idxInShape);
  58808. this._mustUnrotateFixedNormals = true;
  58809. }
  58810. if (this._copy.rotationQuaternion) {
  58811. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58812. }
  58813. else {
  58814. this._yaw = this._copy.rotation.y;
  58815. this._pitch = this._copy.rotation.x;
  58816. this._roll = this._copy.rotation.z;
  58817. this._quaternionRotationYPR();
  58818. }
  58819. this._quaternionToRotationMatrix();
  58820. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58821. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58822. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58823. if (this._copy.translateFromPivot) {
  58824. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58825. }
  58826. else {
  58827. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58828. }
  58829. for (i = 0; i < shape.length; i++) {
  58830. this._vertex.x = shape[i].x;
  58831. this._vertex.y = shape[i].y;
  58832. this._vertex.z = shape[i].z;
  58833. if (options && options.vertexFunction) {
  58834. options.vertexFunction(this._copy, this._vertex, i);
  58835. }
  58836. this._vertex.x *= this._copy.scaling.x;
  58837. this._vertex.y *= this._copy.scaling.y;
  58838. this._vertex.z *= this._copy.scaling.z;
  58839. this._vertex.x -= this._scaledPivot.x;
  58840. this._vertex.y -= this._scaledPivot.y;
  58841. this._vertex.z -= this._scaledPivot.z;
  58842. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58843. this._rotated.addInPlace(this._pivotBackTranslation);
  58844. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58845. if (meshUV) {
  58846. 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);
  58847. u += 2;
  58848. }
  58849. if (this._copy.color) {
  58850. this._color = this._copy.color;
  58851. }
  58852. else if (meshCol && meshCol[c] !== undefined) {
  58853. this._color.r = meshCol[c];
  58854. this._color.g = meshCol[c + 1];
  58855. this._color.b = meshCol[c + 2];
  58856. this._color.a = meshCol[c + 3];
  58857. }
  58858. else {
  58859. this._color.r = 1.0;
  58860. this._color.g = 1.0;
  58861. this._color.b = 1.0;
  58862. this._color.a = 1.0;
  58863. }
  58864. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58865. c += 4;
  58866. if (!this.recomputeNormals && meshNor) {
  58867. this._normal.x = meshNor[n];
  58868. this._normal.y = meshNor[n + 1];
  58869. this._normal.z = meshNor[n + 2];
  58870. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58871. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58872. n += 3;
  58873. }
  58874. }
  58875. for (i = 0; i < meshInd.length; i++) {
  58876. var current_ind = p + meshInd[i];
  58877. indices.push(current_ind);
  58878. if (current_ind > 65535) {
  58879. this._needs32Bits = true;
  58880. }
  58881. }
  58882. if (this._pickable) {
  58883. var nbfaces = meshInd.length / 3;
  58884. for (i = 0; i < nbfaces; i++) {
  58885. this.pickedParticles.push({ idx: idx, faceId: i });
  58886. }
  58887. }
  58888. if (this._depthSort) {
  58889. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58890. }
  58891. return this._copy;
  58892. };
  58893. // returns a shape array from positions array
  58894. SolidParticleSystem.prototype._posToShape = function (positions) {
  58895. var shape = [];
  58896. for (var i = 0; i < positions.length; i += 3) {
  58897. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58898. }
  58899. return shape;
  58900. };
  58901. // returns a shapeUV array from a Vector4 uvs
  58902. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58903. var shapeUV = [];
  58904. if (uvs) {
  58905. for (var i = 0; i < uvs.length; i++)
  58906. shapeUV.push(uvs[i]);
  58907. }
  58908. return shapeUV;
  58909. };
  58910. // adds a new particle object in the particles array
  58911. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58912. if (bInfo === void 0) { bInfo = null; }
  58913. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58914. this.particles.push(sp);
  58915. return sp;
  58916. };
  58917. /**
  58918. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58919. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58920. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58921. * @param nb (positive integer) the number of particles to be created from this model
  58922. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58923. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58924. * @returns the number of shapes in the system
  58925. */
  58926. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58927. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58928. var meshInd = mesh.getIndices();
  58929. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58930. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58931. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58932. var bbInfo;
  58933. if (this._particlesIntersect) {
  58934. bbInfo = mesh.getBoundingInfo();
  58935. }
  58936. var shape = this._posToShape(meshPos);
  58937. var shapeUV = this._uvsToShapeUV(meshUV);
  58938. var posfunc = options ? options.positionFunction : null;
  58939. var vtxfunc = options ? options.vertexFunction : null;
  58940. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58941. // particles
  58942. var sp;
  58943. var currentCopy;
  58944. var idx = this.nbParticles;
  58945. for (var i = 0; i < nb; i++) {
  58946. var currentPos = this._positions.length;
  58947. var currentInd = this._indices.length;
  58948. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58949. if (this._updatable) {
  58950. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58951. sp.position.copyFrom(currentCopy.position);
  58952. sp.rotation.copyFrom(currentCopy.rotation);
  58953. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58954. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58955. }
  58956. if (currentCopy.color && sp.color) {
  58957. sp.color.copyFrom(currentCopy.color);
  58958. }
  58959. sp.scaling.copyFrom(currentCopy.scaling);
  58960. sp.uvs.copyFrom(currentCopy.uvs);
  58961. }
  58962. this._index += shape.length;
  58963. idx++;
  58964. }
  58965. this.nbParticles += nb;
  58966. this._shapeCounter++;
  58967. return this._shapeCounter - 1;
  58968. };
  58969. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58970. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58971. this._resetCopy();
  58972. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58973. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58974. }
  58975. if (this._copy.rotationQuaternion) {
  58976. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58977. }
  58978. else {
  58979. this._yaw = this._copy.rotation.y;
  58980. this._pitch = this._copy.rotation.x;
  58981. this._roll = this._copy.rotation.z;
  58982. this._quaternionRotationYPR();
  58983. }
  58984. this._quaternionToRotationMatrix();
  58985. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58986. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58987. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58988. if (this._copy.translateFromPivot) {
  58989. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58990. }
  58991. else {
  58992. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58993. }
  58994. this._shape = particle._model._shape;
  58995. for (var pt = 0; pt < this._shape.length; pt++) {
  58996. this._vertex.x = this._shape[pt].x;
  58997. this._vertex.y = this._shape[pt].y;
  58998. this._vertex.z = this._shape[pt].z;
  58999. if (particle._model._vertexFunction) {
  59000. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59001. }
  59002. this._vertex.x *= this._copy.scaling.x;
  59003. this._vertex.y *= this._copy.scaling.y;
  59004. this._vertex.z *= this._copy.scaling.z;
  59005. this._vertex.x -= this._scaledPivot.x;
  59006. this._vertex.y -= this._scaledPivot.y;
  59007. this._vertex.z -= this._scaledPivot.z;
  59008. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59009. this._rotated.addInPlace(this._pivotBackTranslation);
  59010. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59011. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59012. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59013. }
  59014. particle.position.x = 0.0;
  59015. particle.position.y = 0.0;
  59016. particle.position.z = 0.0;
  59017. particle.rotation.x = 0.0;
  59018. particle.rotation.y = 0.0;
  59019. particle.rotation.z = 0.0;
  59020. particle.rotationQuaternion = null;
  59021. particle.scaling.x = 1.0;
  59022. particle.scaling.y = 1.0;
  59023. particle.scaling.z = 1.0;
  59024. particle.uvs.x = 0.0;
  59025. particle.uvs.y = 0.0;
  59026. particle.uvs.z = 1.0;
  59027. particle.uvs.w = 1.0;
  59028. particle.pivot.x = 0.0;
  59029. particle.pivot.y = 0.0;
  59030. particle.pivot.z = 0.0;
  59031. particle.translateFromPivot = false;
  59032. particle.parentId = null;
  59033. };
  59034. /**
  59035. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59036. * @returns the SPS.
  59037. */
  59038. SolidParticleSystem.prototype.rebuildMesh = function () {
  59039. for (var p = 0; p < this.particles.length; p++) {
  59040. this._rebuildParticle(this.particles[p]);
  59041. }
  59042. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59043. return this;
  59044. };
  59045. /**
  59046. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59047. * This method calls `updateParticle()` for each particle of the SPS.
  59048. * For an animated SPS, it is usually called within the render loop.
  59049. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59050. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59051. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59052. * @returns the SPS.
  59053. */
  59054. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59055. if (start === void 0) { start = 0; }
  59056. if (end === void 0) { end = this.nbParticles - 1; }
  59057. if (update === void 0) { update = true; }
  59058. if (!this._updatable) {
  59059. return this;
  59060. }
  59061. // custom beforeUpdate
  59062. this.beforeUpdateParticles(start, end, update);
  59063. this._cam_axisX.x = 1.0;
  59064. this._cam_axisX.y = 0.0;
  59065. this._cam_axisX.z = 0.0;
  59066. this._cam_axisY.x = 0.0;
  59067. this._cam_axisY.y = 1.0;
  59068. this._cam_axisY.z = 0.0;
  59069. this._cam_axisZ.x = 0.0;
  59070. this._cam_axisZ.y = 0.0;
  59071. this._cam_axisZ.z = 1.0;
  59072. // cases when the World Matrix is to be computed first
  59073. if (this.billboard || this._depthSort) {
  59074. this.mesh.computeWorldMatrix(true);
  59075. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59076. }
  59077. // if the particles will always face the camera
  59078. if (this.billboard) {
  59079. // compute the camera position and un-rotate it by the current mesh rotation
  59080. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59081. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59082. this._cam_axisZ.normalize();
  59083. // same for camera up vector extracted from the cam view matrix
  59084. var view = this._camera.getViewMatrix(true);
  59085. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59086. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59087. this._cam_axisY.normalize();
  59088. this._cam_axisX.normalize();
  59089. }
  59090. // if depthSort, compute the camera global position in the mesh local system
  59091. if (this._depthSort) {
  59092. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59093. }
  59094. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59095. var idx = 0; // current position index in the global array positions32
  59096. var index = 0; // position start index in the global array positions32 of the current particle
  59097. var colidx = 0; // current color index in the global array colors32
  59098. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59099. var uvidx = 0; // current uv index in the global array uvs32
  59100. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59101. var pt = 0; // current index in the particle model shape
  59102. if (this.mesh.isFacetDataEnabled) {
  59103. this._computeBoundingBox = true;
  59104. }
  59105. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59106. if (this._computeBoundingBox) {
  59107. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59108. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59109. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59110. }
  59111. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59112. if (this.mesh._boundingInfo) {
  59113. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59114. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59115. }
  59116. }
  59117. }
  59118. // particle loop
  59119. index = this.particles[start]._pos;
  59120. var vpos = (index / 3) | 0;
  59121. colorIndex = vpos * 4;
  59122. uvIndex = vpos * 2;
  59123. for (var p = start; p <= end; p++) {
  59124. this._particle = this.particles[p];
  59125. this._shape = this._particle._model._shape;
  59126. this._shapeUV = this._particle._model._shapeUV;
  59127. // call to custom user function to update the particle properties
  59128. this.updateParticle(this._particle);
  59129. // camera-particle distance for depth sorting
  59130. if (this._depthSort && this._depthSortParticles) {
  59131. var dsp = this.depthSortedParticles[p];
  59132. dsp.ind = this._particle._ind;
  59133. dsp.indicesLength = this._particle._model._indicesLength;
  59134. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59135. }
  59136. // skip the computations for inactive or already invisible particles
  59137. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59138. // increment indexes for the next particle
  59139. pt = this._shape.length;
  59140. index += pt * 3;
  59141. colorIndex += pt * 4;
  59142. uvIndex += pt * 2;
  59143. continue;
  59144. }
  59145. if (this._particle.isVisible) {
  59146. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59147. this._particleHasParent = (this._particle.parentId !== null);
  59148. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59149. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59150. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59151. // particle rotation matrix
  59152. if (this.billboard) {
  59153. this._particle.rotation.x = 0.0;
  59154. this._particle.rotation.y = 0.0;
  59155. }
  59156. if (this._computeParticleRotation || this.billboard) {
  59157. if (this._particle.rotationQuaternion) {
  59158. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59159. }
  59160. else {
  59161. this._yaw = this._particle.rotation.y;
  59162. this._pitch = this._particle.rotation.x;
  59163. this._roll = this._particle.rotation.z;
  59164. this._quaternionRotationYPR();
  59165. }
  59166. this._quaternionToRotationMatrix();
  59167. }
  59168. if (this._particleHasParent) {
  59169. this._parent = this.particles[this._particle.parentId];
  59170. 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];
  59171. 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];
  59172. 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];
  59173. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59174. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59175. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59176. if (this._computeParticleRotation || this.billboard) {
  59177. 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];
  59178. 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];
  59179. 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];
  59180. 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];
  59181. 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];
  59182. 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];
  59183. 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];
  59184. 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];
  59185. 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];
  59186. }
  59187. }
  59188. else {
  59189. this._particle._globalPosition.x = this._particle.position.x;
  59190. this._particle._globalPosition.y = this._particle.position.y;
  59191. this._particle._globalPosition.z = this._particle.position.z;
  59192. if (this._computeParticleRotation || this.billboard) {
  59193. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59194. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59195. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59196. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59197. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59198. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59199. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59200. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59201. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59202. }
  59203. }
  59204. if (this._particle.translateFromPivot) {
  59205. this._pivotBackTranslation.x = 0.0;
  59206. this._pivotBackTranslation.y = 0.0;
  59207. this._pivotBackTranslation.z = 0.0;
  59208. }
  59209. else {
  59210. this._pivotBackTranslation.x = this._scaledPivot.x;
  59211. this._pivotBackTranslation.y = this._scaledPivot.y;
  59212. this._pivotBackTranslation.z = this._scaledPivot.z;
  59213. }
  59214. // particle vertex loop
  59215. for (pt = 0; pt < this._shape.length; pt++) {
  59216. idx = index + pt * 3;
  59217. colidx = colorIndex + pt * 4;
  59218. uvidx = uvIndex + pt * 2;
  59219. this._vertex.x = this._shape[pt].x;
  59220. this._vertex.y = this._shape[pt].y;
  59221. this._vertex.z = this._shape[pt].z;
  59222. if (this._computeParticleVertex) {
  59223. this.updateParticleVertex(this._particle, this._vertex, pt);
  59224. }
  59225. // positions
  59226. this._vertex.x *= this._particle.scaling.x;
  59227. this._vertex.y *= this._particle.scaling.y;
  59228. this._vertex.z *= this._particle.scaling.z;
  59229. this._vertex.x -= this._scaledPivot.x;
  59230. this._vertex.y -= this._scaledPivot.y;
  59231. this._vertex.z -= this._scaledPivot.z;
  59232. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59233. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59234. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59235. this._rotated.x += this._pivotBackTranslation.x;
  59236. this._rotated.y += this._pivotBackTranslation.y;
  59237. this._rotated.z += this._pivotBackTranslation.z;
  59238. 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;
  59239. 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;
  59240. 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;
  59241. if (this._computeBoundingBox) {
  59242. if (this._positions32[idx] < this._minimum.x) {
  59243. this._minimum.x = this._positions32[idx];
  59244. }
  59245. if (this._positions32[idx] > this._maximum.x) {
  59246. this._maximum.x = this._positions32[idx];
  59247. }
  59248. if (this._positions32[idx + 1] < this._minimum.y) {
  59249. this._minimum.y = this._positions32[idx + 1];
  59250. }
  59251. if (this._positions32[idx + 1] > this._maximum.y) {
  59252. this._maximum.y = this._positions32[idx + 1];
  59253. }
  59254. if (this._positions32[idx + 2] < this._minimum.z) {
  59255. this._minimum.z = this._positions32[idx + 2];
  59256. }
  59257. if (this._positions32[idx + 2] > this._maximum.z) {
  59258. this._maximum.z = this._positions32[idx + 2];
  59259. }
  59260. }
  59261. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59262. if (!this._computeParticleVertex) {
  59263. this._normal.x = this._fixedNormal32[idx];
  59264. this._normal.y = this._fixedNormal32[idx + 1];
  59265. this._normal.z = this._fixedNormal32[idx + 2];
  59266. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59267. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59268. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59269. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59270. 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;
  59271. 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;
  59272. }
  59273. if (this._computeParticleColor && this._particle.color) {
  59274. this._colors32[colidx] = this._particle.color.r;
  59275. this._colors32[colidx + 1] = this._particle.color.g;
  59276. this._colors32[colidx + 2] = this._particle.color.b;
  59277. this._colors32[colidx + 3] = this._particle.color.a;
  59278. }
  59279. if (this._computeParticleTexture) {
  59280. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59281. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59282. }
  59283. }
  59284. }
  59285. // particle just set invisible : scaled to zero and positioned at the origin
  59286. else {
  59287. this._particle._stillInvisible = true; // mark the particle as invisible
  59288. for (pt = 0; pt < this._shape.length; pt++) {
  59289. idx = index + pt * 3;
  59290. colidx = colorIndex + pt * 4;
  59291. uvidx = uvIndex + pt * 2;
  59292. this._positions32[idx] = 0.0;
  59293. this._positions32[idx + 1] = 0.0;
  59294. this._positions32[idx + 2] = 0.0;
  59295. this._normals32[idx] = 0.0;
  59296. this._normals32[idx + 1] = 0.0;
  59297. this._normals32[idx + 2] = 0.0;
  59298. if (this._computeParticleColor && this._particle.color) {
  59299. this._colors32[colidx] = this._particle.color.r;
  59300. this._colors32[colidx + 1] = this._particle.color.g;
  59301. this._colors32[colidx + 2] = this._particle.color.b;
  59302. this._colors32[colidx + 3] = this._particle.color.a;
  59303. }
  59304. if (this._computeParticleTexture) {
  59305. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59306. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59307. }
  59308. }
  59309. }
  59310. // if the particle intersections must be computed : update the bbInfo
  59311. if (this._particlesIntersect) {
  59312. var bInfo = this._particle._boundingInfo;
  59313. var bBox = bInfo.boundingBox;
  59314. var bSphere = bInfo.boundingSphere;
  59315. if (!this._bSphereOnly) {
  59316. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59317. for (var b = 0; b < bBox.vectors.length; b++) {
  59318. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59319. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59320. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59321. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59322. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59323. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59324. 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;
  59325. 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;
  59326. 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;
  59327. }
  59328. bBox._update(this.mesh._worldMatrix);
  59329. }
  59330. // place and scale the particle bouding sphere in the SPS local system, then update it
  59331. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59332. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59333. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59334. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59335. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59336. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59337. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59338. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59339. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59340. 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));
  59341. bSphere._update(this.mesh._worldMatrix);
  59342. }
  59343. // increment indexes for the next particle
  59344. index = idx + 3;
  59345. colorIndex = colidx + 4;
  59346. uvIndex = uvidx + 2;
  59347. }
  59348. // if the VBO must be updated
  59349. if (update) {
  59350. if (this._computeParticleColor) {
  59351. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59352. }
  59353. if (this._computeParticleTexture) {
  59354. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59355. }
  59356. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59357. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59358. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59359. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59360. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59361. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59362. for (var i = 0; i < this._normals32.length; i++) {
  59363. this._fixedNormal32[i] = this._normals32[i];
  59364. }
  59365. }
  59366. if (!this.mesh.areNormalsFrozen) {
  59367. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59368. }
  59369. }
  59370. if (this._depthSort && this._depthSortParticles) {
  59371. this.depthSortedParticles.sort(this._depthSortFunction);
  59372. var dspl = this.depthSortedParticles.length;
  59373. var sorted = 0;
  59374. var lind = 0;
  59375. var sind = 0;
  59376. var sid = 0;
  59377. for (sorted = 0; sorted < dspl; sorted++) {
  59378. lind = this.depthSortedParticles[sorted].indicesLength;
  59379. sind = this.depthSortedParticles[sorted].ind;
  59380. for (var i = 0; i < lind; i++) {
  59381. this._indices32[sid] = this._indices[sind + i];
  59382. sid++;
  59383. }
  59384. }
  59385. this.mesh.updateIndices(this._indices32);
  59386. }
  59387. }
  59388. if (this._computeBoundingBox) {
  59389. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59390. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59391. }
  59392. this.afterUpdateParticles(start, end, update);
  59393. return this;
  59394. };
  59395. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59396. this._halfroll = this._roll * 0.5;
  59397. this._halfpitch = this._pitch * 0.5;
  59398. this._halfyaw = this._yaw * 0.5;
  59399. this._sinRoll = Math.sin(this._halfroll);
  59400. this._cosRoll = Math.cos(this._halfroll);
  59401. this._sinPitch = Math.sin(this._halfpitch);
  59402. this._cosPitch = Math.cos(this._halfpitch);
  59403. this._sinYaw = Math.sin(this._halfyaw);
  59404. this._cosYaw = Math.cos(this._halfyaw);
  59405. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59406. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59407. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59408. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59409. };
  59410. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59411. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59412. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59413. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59414. this._rotMatrix.m[3] = 0;
  59415. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59416. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59417. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59418. this._rotMatrix.m[7] = 0;
  59419. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59420. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59421. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59422. this._rotMatrix.m[11] = 0;
  59423. this._rotMatrix.m[12] = 0;
  59424. this._rotMatrix.m[13] = 0;
  59425. this._rotMatrix.m[14] = 0;
  59426. this._rotMatrix.m[15] = 1.0;
  59427. };
  59428. /**
  59429. * Disposes the SPS.
  59430. */
  59431. SolidParticleSystem.prototype.dispose = function () {
  59432. this.mesh.dispose();
  59433. this.vars = null;
  59434. // drop references to internal big arrays for the GC
  59435. this._positions = null;
  59436. this._indices = null;
  59437. this._normals = null;
  59438. this._uvs = null;
  59439. this._colors = null;
  59440. this._indices32 = null;
  59441. this._positions32 = null;
  59442. this._normals32 = null;
  59443. this._fixedNormal32 = null;
  59444. this._uvs32 = null;
  59445. this._colors32 = null;
  59446. this.pickedParticles = null;
  59447. };
  59448. /**
  59449. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59450. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59451. * @returns the SPS.
  59452. */
  59453. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59454. if (!this._isVisibilityBoxLocked) {
  59455. this.mesh.refreshBoundingInfo();
  59456. }
  59457. return this;
  59458. };
  59459. /**
  59460. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59461. * @param size the size (float) of the visibility box
  59462. * note : this doesn't lock the SPS mesh bounding box.
  59463. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59464. */
  59465. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59466. var vis = size / 2;
  59467. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59468. };
  59469. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59470. /**
  59471. * Gets whether the SPS as always visible or not
  59472. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59473. */
  59474. get: function () {
  59475. return this._alwaysVisible;
  59476. },
  59477. /**
  59478. * Sets the SPS as always visible or not
  59479. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59480. */
  59481. set: function (val) {
  59482. this._alwaysVisible = val;
  59483. this.mesh.alwaysSelectAsActiveMesh = val;
  59484. },
  59485. enumerable: true,
  59486. configurable: true
  59487. });
  59488. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59489. /**
  59490. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59491. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59492. */
  59493. get: function () {
  59494. return this._isVisibilityBoxLocked;
  59495. },
  59496. /**
  59497. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59498. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59499. */
  59500. set: function (val) {
  59501. this._isVisibilityBoxLocked = val;
  59502. var boundingInfo = this.mesh.getBoundingInfo();
  59503. boundingInfo.isLocked = val;
  59504. },
  59505. enumerable: true,
  59506. configurable: true
  59507. });
  59508. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59509. /**
  59510. * Gets if `setParticles()` computes the particle rotations or not.
  59511. * Default value : true. The SPS is faster when it's set to false.
  59512. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59513. */
  59514. get: function () {
  59515. return this._computeParticleRotation;
  59516. },
  59517. /**
  59518. * Tells to `setParticles()` to compute the particle rotations or not.
  59519. * Default value : true. The SPS is faster when it's set to false.
  59520. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59521. */
  59522. set: function (val) {
  59523. this._computeParticleRotation = val;
  59524. },
  59525. enumerable: true,
  59526. configurable: true
  59527. });
  59528. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59529. /**
  59530. * Gets if `setParticles()` computes the particle colors or not.
  59531. * Default value : true. The SPS is faster when it's set to false.
  59532. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59533. */
  59534. get: function () {
  59535. return this._computeParticleColor;
  59536. },
  59537. /**
  59538. * Tells to `setParticles()` to compute the particle colors or not.
  59539. * Default value : true. The SPS is faster when it's set to false.
  59540. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59541. */
  59542. set: function (val) {
  59543. this._computeParticleColor = val;
  59544. },
  59545. enumerable: true,
  59546. configurable: true
  59547. });
  59548. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59549. /**
  59550. * Gets if `setParticles()` computes the particle textures or not.
  59551. * Default value : true. The SPS is faster when it's set to false.
  59552. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59553. */
  59554. get: function () {
  59555. return this._computeParticleTexture;
  59556. },
  59557. set: function (val) {
  59558. this._computeParticleTexture = val;
  59559. },
  59560. enumerable: true,
  59561. configurable: true
  59562. });
  59563. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59564. /**
  59565. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59566. * Default value : false. The SPS is faster when it's set to false.
  59567. * Note : the particle custom vertex positions aren't stored values.
  59568. */
  59569. get: function () {
  59570. return this._computeParticleVertex;
  59571. },
  59572. /**
  59573. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59574. * Default value : false. The SPS is faster when it's set to false.
  59575. * Note : the particle custom vertex positions aren't stored values.
  59576. */
  59577. set: function (val) {
  59578. this._computeParticleVertex = val;
  59579. },
  59580. enumerable: true,
  59581. configurable: true
  59582. });
  59583. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59584. /**
  59585. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59586. */
  59587. get: function () {
  59588. return this._computeBoundingBox;
  59589. },
  59590. /**
  59591. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59592. */
  59593. set: function (val) {
  59594. this._computeBoundingBox = val;
  59595. },
  59596. enumerable: true,
  59597. configurable: true
  59598. });
  59599. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59600. /**
  59601. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59602. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59603. * Default : `true`
  59604. */
  59605. get: function () {
  59606. return this._depthSortParticles;
  59607. },
  59608. /**
  59609. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59610. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59611. * Default : `true`
  59612. */
  59613. set: function (val) {
  59614. this._depthSortParticles = val;
  59615. },
  59616. enumerable: true,
  59617. configurable: true
  59618. });
  59619. // =======================================================================
  59620. // Particle behavior logic
  59621. // these following methods may be overwritten by the user to fit his needs
  59622. /**
  59623. * This function does nothing. It may be overwritten to set all the particle first values.
  59624. * The SPS doesn't call this function, you may have to call it by your own.
  59625. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59626. */
  59627. SolidParticleSystem.prototype.initParticles = function () {
  59628. };
  59629. /**
  59630. * This function does nothing. It may be overwritten to recycle a particle.
  59631. * The SPS doesn't call this function, you may have to call it by your own.
  59632. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59633. * @param particle The particle to recycle
  59634. * @returns the recycled particle
  59635. */
  59636. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59637. return particle;
  59638. };
  59639. /**
  59640. * Updates a particle : this function should be overwritten by the user.
  59641. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59642. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59643. * @example : just set a particle position or velocity and recycle conditions
  59644. * @param particle The particle to update
  59645. * @returns the updated particle
  59646. */
  59647. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59648. return particle;
  59649. };
  59650. /**
  59651. * Updates a vertex of a particle : it can be overwritten by the user.
  59652. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59653. * @param particle the current particle
  59654. * @param vertex the current index of the current particle
  59655. * @param pt the index of the current vertex in the particle shape
  59656. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59657. * @example : just set a vertex particle position
  59658. * @returns the updated vertex
  59659. */
  59660. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59661. return vertex;
  59662. };
  59663. /**
  59664. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59665. * This does nothing and may be overwritten by the user.
  59666. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59667. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59668. * @param update the boolean update value actually passed to setParticles()
  59669. */
  59670. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59671. };
  59672. /**
  59673. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59674. * This will be passed three parameters.
  59675. * This does nothing and may be overwritten by the user.
  59676. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59677. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59678. * @param update the boolean update value actually passed to setParticles()
  59679. */
  59680. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59681. };
  59682. return SolidParticleSystem;
  59683. }());
  59684. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59685. })(BABYLON || (BABYLON = {}));
  59686. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59687. var BABYLON;
  59688. (function (BABYLON) {
  59689. var ShaderMaterial = /** @class */ (function (_super) {
  59690. __extends(ShaderMaterial, _super);
  59691. function ShaderMaterial(name, scene, shaderPath, options) {
  59692. var _this = _super.call(this, name, scene) || this;
  59693. _this._textures = {};
  59694. _this._textureArrays = {};
  59695. _this._floats = {};
  59696. _this._ints = {};
  59697. _this._floatsArrays = {};
  59698. _this._colors3 = {};
  59699. _this._colors3Arrays = {};
  59700. _this._colors4 = {};
  59701. _this._vectors2 = {};
  59702. _this._vectors3 = {};
  59703. _this._vectors4 = {};
  59704. _this._matrices = {};
  59705. _this._matrices3x3 = {};
  59706. _this._matrices2x2 = {};
  59707. _this._vectors2Arrays = {};
  59708. _this._vectors3Arrays = {};
  59709. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59710. _this._shaderPath = shaderPath;
  59711. options.needAlphaBlending = options.needAlphaBlending || false;
  59712. options.needAlphaTesting = options.needAlphaTesting || false;
  59713. options.attributes = options.attributes || ["position", "normal", "uv"];
  59714. options.uniforms = options.uniforms || ["worldViewProjection"];
  59715. options.uniformBuffers = options.uniformBuffers || [];
  59716. options.samplers = options.samplers || [];
  59717. options.defines = options.defines || [];
  59718. _this._options = options;
  59719. return _this;
  59720. }
  59721. ShaderMaterial.prototype.getClassName = function () {
  59722. return "ShaderMaterial";
  59723. };
  59724. ShaderMaterial.prototype.needAlphaBlending = function () {
  59725. return this._options.needAlphaBlending;
  59726. };
  59727. ShaderMaterial.prototype.needAlphaTesting = function () {
  59728. return this._options.needAlphaTesting;
  59729. };
  59730. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59731. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59732. this._options.uniforms.push(uniformName);
  59733. }
  59734. };
  59735. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59736. if (this._options.samplers.indexOf(name) === -1) {
  59737. this._options.samplers.push(name);
  59738. }
  59739. this._textures[name] = texture;
  59740. return this;
  59741. };
  59742. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59743. if (this._options.samplers.indexOf(name) === -1) {
  59744. this._options.samplers.push(name);
  59745. }
  59746. this._checkUniform(name);
  59747. this._textureArrays[name] = textures;
  59748. return this;
  59749. };
  59750. ShaderMaterial.prototype.setFloat = function (name, value) {
  59751. this._checkUniform(name);
  59752. this._floats[name] = value;
  59753. return this;
  59754. };
  59755. ShaderMaterial.prototype.setInt = function (name, value) {
  59756. this._checkUniform(name);
  59757. this._ints[name] = value;
  59758. return this;
  59759. };
  59760. ShaderMaterial.prototype.setFloats = function (name, value) {
  59761. this._checkUniform(name);
  59762. this._floatsArrays[name] = value;
  59763. return this;
  59764. };
  59765. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59766. this._checkUniform(name);
  59767. this._colors3[name] = value;
  59768. return this;
  59769. };
  59770. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59771. this._checkUniform(name);
  59772. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59773. color.toArray(arr, arr.length);
  59774. return arr;
  59775. }, []);
  59776. return this;
  59777. };
  59778. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59779. this._checkUniform(name);
  59780. this._colors4[name] = value;
  59781. return this;
  59782. };
  59783. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59784. this._checkUniform(name);
  59785. this._vectors2[name] = value;
  59786. return this;
  59787. };
  59788. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59789. this._checkUniform(name);
  59790. this._vectors3[name] = value;
  59791. return this;
  59792. };
  59793. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59794. this._checkUniform(name);
  59795. this._vectors4[name] = value;
  59796. return this;
  59797. };
  59798. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59799. this._checkUniform(name);
  59800. this._matrices[name] = value;
  59801. return this;
  59802. };
  59803. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59804. this._checkUniform(name);
  59805. this._matrices3x3[name] = value;
  59806. return this;
  59807. };
  59808. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59809. this._checkUniform(name);
  59810. this._matrices2x2[name] = value;
  59811. return this;
  59812. };
  59813. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59814. this._checkUniform(name);
  59815. this._vectors2Arrays[name] = value;
  59816. return this;
  59817. };
  59818. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59819. this._checkUniform(name);
  59820. this._vectors3Arrays[name] = value;
  59821. return this;
  59822. };
  59823. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59824. if (!mesh) {
  59825. return true;
  59826. }
  59827. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59828. return false;
  59829. }
  59830. return false;
  59831. };
  59832. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59833. var scene = this.getScene();
  59834. var engine = scene.getEngine();
  59835. if (!this.checkReadyOnEveryCall) {
  59836. if (this._renderId === scene.getRenderId()) {
  59837. if (this._checkCache(scene, mesh, useInstances)) {
  59838. return true;
  59839. }
  59840. }
  59841. }
  59842. // Instances
  59843. var defines = [];
  59844. var attribs = [];
  59845. var fallbacks = new BABYLON.EffectFallbacks();
  59846. if (useInstances) {
  59847. defines.push("#define INSTANCES");
  59848. }
  59849. for (var index = 0; index < this._options.defines.length; index++) {
  59850. defines.push(this._options.defines[index]);
  59851. }
  59852. for (var index = 0; index < this._options.attributes.length; index++) {
  59853. attribs.push(this._options.attributes[index]);
  59854. }
  59855. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59856. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59857. defines.push("#define VERTEXCOLOR");
  59858. }
  59859. // Bones
  59860. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59863. if (mesh.numBoneInfluencers > 4) {
  59864. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59865. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59866. }
  59867. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59868. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59869. fallbacks.addCPUSkinningFallback(0, mesh);
  59870. if (this._options.uniforms.indexOf("mBones") === -1) {
  59871. this._options.uniforms.push("mBones");
  59872. }
  59873. }
  59874. else {
  59875. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59876. }
  59877. // Textures
  59878. for (var name in this._textures) {
  59879. if (!this._textures[name].isReady()) {
  59880. return false;
  59881. }
  59882. }
  59883. // Alpha test
  59884. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59885. defines.push("#define ALPHATEST");
  59886. }
  59887. var previousEffect = this._effect;
  59888. var join = defines.join("\n");
  59889. this._effect = engine.createEffect(this._shaderPath, {
  59890. attributes: attribs,
  59891. uniformsNames: this._options.uniforms,
  59892. uniformBuffersNames: this._options.uniformBuffers,
  59893. samplers: this._options.samplers,
  59894. defines: join,
  59895. fallbacks: fallbacks,
  59896. onCompiled: this.onCompiled,
  59897. onError: this.onError
  59898. }, engine);
  59899. if (!this._effect.isReady()) {
  59900. return false;
  59901. }
  59902. if (previousEffect !== this._effect) {
  59903. scene.resetCachedMaterial();
  59904. }
  59905. this._renderId = scene.getRenderId();
  59906. return true;
  59907. };
  59908. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59909. var scene = this.getScene();
  59910. if (!this._effect) {
  59911. return;
  59912. }
  59913. if (this._options.uniforms.indexOf("world") !== -1) {
  59914. this._effect.setMatrix("world", world);
  59915. }
  59916. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59917. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59918. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59919. }
  59920. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59921. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59922. }
  59923. };
  59924. ShaderMaterial.prototype.bind = function (world, mesh) {
  59925. // Std values
  59926. this.bindOnlyWorldMatrix(world);
  59927. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59928. if (this._options.uniforms.indexOf("view") !== -1) {
  59929. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59930. }
  59931. if (this._options.uniforms.indexOf("projection") !== -1) {
  59932. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59933. }
  59934. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59935. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59936. }
  59937. // Bones
  59938. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59939. var name;
  59940. // Texture
  59941. for (name in this._textures) {
  59942. this._effect.setTexture(name, this._textures[name]);
  59943. }
  59944. // Texture arrays
  59945. for (name in this._textureArrays) {
  59946. this._effect.setTextureArray(name, this._textureArrays[name]);
  59947. }
  59948. // Int
  59949. for (name in this._ints) {
  59950. this._effect.setInt(name, this._ints[name]);
  59951. }
  59952. // Float
  59953. for (name in this._floats) {
  59954. this._effect.setFloat(name, this._floats[name]);
  59955. }
  59956. // Floats
  59957. for (name in this._floatsArrays) {
  59958. this._effect.setArray(name, this._floatsArrays[name]);
  59959. }
  59960. // Color3
  59961. for (name in this._colors3) {
  59962. this._effect.setColor3(name, this._colors3[name]);
  59963. }
  59964. for (name in this._colors3Arrays) {
  59965. this._effect.setArray3(name, this._colors3Arrays[name]);
  59966. }
  59967. // Color4
  59968. for (name in this._colors4) {
  59969. var color = this._colors4[name];
  59970. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59971. }
  59972. // Vector2
  59973. for (name in this._vectors2) {
  59974. this._effect.setVector2(name, this._vectors2[name]);
  59975. }
  59976. // Vector3
  59977. for (name in this._vectors3) {
  59978. this._effect.setVector3(name, this._vectors3[name]);
  59979. }
  59980. // Vector4
  59981. for (name in this._vectors4) {
  59982. this._effect.setVector4(name, this._vectors4[name]);
  59983. }
  59984. // Matrix
  59985. for (name in this._matrices) {
  59986. this._effect.setMatrix(name, this._matrices[name]);
  59987. }
  59988. // Matrix 3x3
  59989. for (name in this._matrices3x3) {
  59990. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59991. }
  59992. // Matrix 2x2
  59993. for (name in this._matrices2x2) {
  59994. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59995. }
  59996. // Vector2Array
  59997. for (name in this._vectors2Arrays) {
  59998. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59999. }
  60000. // Vector3Array
  60001. for (name in this._vectors3Arrays) {
  60002. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60003. }
  60004. }
  60005. this._afterBind(mesh);
  60006. };
  60007. ShaderMaterial.prototype.getActiveTextures = function () {
  60008. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60009. for (var name in this._textures) {
  60010. activeTextures.push(this._textures[name]);
  60011. }
  60012. for (var name in this._textureArrays) {
  60013. var array = this._textureArrays[name];
  60014. for (var index = 0; index < array.length; index++) {
  60015. activeTextures.push(array[index]);
  60016. }
  60017. }
  60018. return activeTextures;
  60019. };
  60020. ShaderMaterial.prototype.hasTexture = function (texture) {
  60021. if (_super.prototype.hasTexture.call(this, texture)) {
  60022. return true;
  60023. }
  60024. for (var name in this._textures) {
  60025. if (this._textures[name] === texture) {
  60026. return true;
  60027. }
  60028. }
  60029. for (var name in this._textureArrays) {
  60030. var array = this._textureArrays[name];
  60031. for (var index = 0; index < array.length; index++) {
  60032. if (array[index] === texture) {
  60033. return true;
  60034. }
  60035. }
  60036. }
  60037. return false;
  60038. };
  60039. ShaderMaterial.prototype.clone = function (name) {
  60040. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60041. return newShaderMaterial;
  60042. };
  60043. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60044. if (forceDisposeTextures) {
  60045. var name;
  60046. for (name in this._textures) {
  60047. this._textures[name].dispose();
  60048. }
  60049. for (name in this._textureArrays) {
  60050. var array = this._textureArrays[name];
  60051. for (var index = 0; index < array.length; index++) {
  60052. array[index].dispose();
  60053. }
  60054. }
  60055. }
  60056. this._textures = {};
  60057. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60058. };
  60059. ShaderMaterial.prototype.serialize = function () {
  60060. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60061. serializationObject.customType = "BABYLON.ShaderMaterial";
  60062. serializationObject.options = this._options;
  60063. serializationObject.shaderPath = this._shaderPath;
  60064. var name;
  60065. // Texture
  60066. serializationObject.textures = {};
  60067. for (name in this._textures) {
  60068. serializationObject.textures[name] = this._textures[name].serialize();
  60069. }
  60070. // Texture arrays
  60071. serializationObject.textureArrays = {};
  60072. for (name in this._textureArrays) {
  60073. serializationObject.textureArrays[name] = [];
  60074. var array = this._textureArrays[name];
  60075. for (var index = 0; index < array.length; index++) {
  60076. serializationObject.textureArrays[name].push(array[index].serialize());
  60077. }
  60078. }
  60079. // Float
  60080. serializationObject.floats = {};
  60081. for (name in this._floats) {
  60082. serializationObject.floats[name] = this._floats[name];
  60083. }
  60084. // Float s
  60085. serializationObject.FloatArrays = {};
  60086. for (name in this._floatsArrays) {
  60087. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60088. }
  60089. // Color3
  60090. serializationObject.colors3 = {};
  60091. for (name in this._colors3) {
  60092. serializationObject.colors3[name] = this._colors3[name].asArray();
  60093. }
  60094. // Color3 array
  60095. serializationObject.colors3Arrays = {};
  60096. for (name in this._colors3Arrays) {
  60097. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60098. }
  60099. // Color4
  60100. serializationObject.colors4 = {};
  60101. for (name in this._colors4) {
  60102. serializationObject.colors4[name] = this._colors4[name].asArray();
  60103. }
  60104. // Vector2
  60105. serializationObject.vectors2 = {};
  60106. for (name in this._vectors2) {
  60107. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60108. }
  60109. // Vector3
  60110. serializationObject.vectors3 = {};
  60111. for (name in this._vectors3) {
  60112. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60113. }
  60114. // Vector4
  60115. serializationObject.vectors4 = {};
  60116. for (name in this._vectors4) {
  60117. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60118. }
  60119. // Matrix
  60120. serializationObject.matrices = {};
  60121. for (name in this._matrices) {
  60122. serializationObject.matrices[name] = this._matrices[name].asArray();
  60123. }
  60124. // Matrix 3x3
  60125. serializationObject.matrices3x3 = {};
  60126. for (name in this._matrices3x3) {
  60127. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60128. }
  60129. // Matrix 2x2
  60130. serializationObject.matrices2x2 = {};
  60131. for (name in this._matrices2x2) {
  60132. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60133. }
  60134. // Vector2Array
  60135. serializationObject.vectors2Arrays = {};
  60136. for (name in this._vectors2Arrays) {
  60137. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60138. }
  60139. // Vector3Array
  60140. serializationObject.vectors3Arrays = {};
  60141. for (name in this._vectors3Arrays) {
  60142. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60143. }
  60144. return serializationObject;
  60145. };
  60146. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60147. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60148. var name;
  60149. // Texture
  60150. for (name in source.textures) {
  60151. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60152. }
  60153. // Texture arrays
  60154. for (name in source.textureArrays) {
  60155. var array = source.textureArrays[name];
  60156. var textureArray = new Array();
  60157. for (var index = 0; index < array.length; index++) {
  60158. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60159. }
  60160. material.setTextureArray(name, textureArray);
  60161. }
  60162. // Float
  60163. for (name in source.floats) {
  60164. material.setFloat(name, source.floats[name]);
  60165. }
  60166. // Float s
  60167. for (name in source.floatsArrays) {
  60168. material.setFloats(name, source.floatsArrays[name]);
  60169. }
  60170. // Color3
  60171. for (name in source.colors3) {
  60172. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60173. }
  60174. // Color3 arrays
  60175. for (name in source.colors3Arrays) {
  60176. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60177. if (i % 3 === 0) {
  60178. arr.push([num]);
  60179. }
  60180. else {
  60181. arr[arr.length - 1].push(num);
  60182. }
  60183. return arr;
  60184. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60185. material.setColor3Array(name, colors);
  60186. }
  60187. // Color4
  60188. for (name in source.colors4) {
  60189. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60190. }
  60191. // Vector2
  60192. for (name in source.vectors2) {
  60193. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60194. }
  60195. // Vector3
  60196. for (name in source.vectors3) {
  60197. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60198. }
  60199. // Vector4
  60200. for (name in source.vectors4) {
  60201. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60202. }
  60203. // Matrix
  60204. for (name in source.matrices) {
  60205. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60206. }
  60207. // Matrix 3x3
  60208. for (name in source.matrices3x3) {
  60209. material.setMatrix3x3(name, source.matrices3x3[name]);
  60210. }
  60211. // Matrix 2x2
  60212. for (name in source.matrices2x2) {
  60213. material.setMatrix2x2(name, source.matrices2x2[name]);
  60214. }
  60215. // Vector2Array
  60216. for (name in source.vectors2Arrays) {
  60217. material.setArray2(name, source.vectors2Arrays[name]);
  60218. }
  60219. // Vector3Array
  60220. for (name in source.vectors3Arrays) {
  60221. material.setArray3(name, source.vectors3Arrays[name]);
  60222. }
  60223. return material;
  60224. };
  60225. return ShaderMaterial;
  60226. }(BABYLON.Material));
  60227. BABYLON.ShaderMaterial = ShaderMaterial;
  60228. })(BABYLON || (BABYLON = {}));
  60229. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60230. var BABYLON;
  60231. (function (BABYLON) {
  60232. var GroundMesh = /** @class */ (function (_super) {
  60233. __extends(GroundMesh, _super);
  60234. function GroundMesh(name, scene) {
  60235. var _this = _super.call(this, name, scene) || this;
  60236. _this.generateOctree = false;
  60237. return _this;
  60238. }
  60239. GroundMesh.prototype.getClassName = function () {
  60240. return "GroundMesh";
  60241. };
  60242. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60243. get: function () {
  60244. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60245. },
  60246. enumerable: true,
  60247. configurable: true
  60248. });
  60249. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60250. get: function () {
  60251. return this._subdivisionsX;
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60257. get: function () {
  60258. return this._subdivisionsY;
  60259. },
  60260. enumerable: true,
  60261. configurable: true
  60262. });
  60263. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60264. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60265. this._subdivisionsX = chunksCount;
  60266. this._subdivisionsY = chunksCount;
  60267. this.subdivide(chunksCount);
  60268. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60269. };
  60270. /**
  60271. * Returns a height (y) value in the Worl system :
  60272. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60273. * Returns the ground y position if (x, z) are outside the ground surface.
  60274. */
  60275. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60276. var world = this.getWorldMatrix();
  60277. var invMat = BABYLON.Tmp.Matrix[5];
  60278. world.invertToRef(invMat);
  60279. var tmpVect = BABYLON.Tmp.Vector3[8];
  60280. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60281. x = tmpVect.x;
  60282. z = tmpVect.z;
  60283. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60284. return this.position.y;
  60285. }
  60286. if (!this._heightQuads || this._heightQuads.length == 0) {
  60287. this._initHeightQuads();
  60288. this._computeHeightQuads();
  60289. }
  60290. var facet = this._getFacetAt(x, z);
  60291. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60292. // return y in the World system
  60293. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60294. return tmpVect.y;
  60295. };
  60296. /**
  60297. * Returns a normalized vector (Vector3) orthogonal to the ground
  60298. * at the ground coordinates (x, z) expressed in the World system.
  60299. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60300. */
  60301. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60302. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60303. this.getNormalAtCoordinatesToRef(x, z, normal);
  60304. return normal;
  60305. };
  60306. /**
  60307. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60308. * at the ground coordinates (x, z) expressed in the World system.
  60309. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60310. * Returns the GroundMesh.
  60311. */
  60312. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60313. var world = this.getWorldMatrix();
  60314. var tmpMat = BABYLON.Tmp.Matrix[5];
  60315. world.invertToRef(tmpMat);
  60316. var tmpVect = BABYLON.Tmp.Vector3[8];
  60317. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60318. x = tmpVect.x;
  60319. z = tmpVect.z;
  60320. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60321. return this;
  60322. }
  60323. if (!this._heightQuads || this._heightQuads.length == 0) {
  60324. this._initHeightQuads();
  60325. this._computeHeightQuads();
  60326. }
  60327. var facet = this._getFacetAt(x, z);
  60328. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60329. return this;
  60330. };
  60331. /**
  60332. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60333. * if the ground has been updated.
  60334. * This can be used in the render loop.
  60335. * Returns the GroundMesh.
  60336. */
  60337. GroundMesh.prototype.updateCoordinateHeights = function () {
  60338. if (!this._heightQuads || this._heightQuads.length == 0) {
  60339. this._initHeightQuads();
  60340. }
  60341. this._computeHeightQuads();
  60342. return this;
  60343. };
  60344. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60345. GroundMesh.prototype._getFacetAt = function (x, z) {
  60346. // retrieve col and row from x, z coordinates in the ground local system
  60347. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60348. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60349. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60350. var facet;
  60351. if (z < quad.slope.x * x + quad.slope.y) {
  60352. facet = quad.facet1;
  60353. }
  60354. else {
  60355. facet = quad.facet2;
  60356. }
  60357. return facet;
  60358. };
  60359. // Creates and populates the heightMap array with "facet" elements :
  60360. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60361. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60362. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60363. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60364. // Returns the GroundMesh.
  60365. GroundMesh.prototype._initHeightQuads = function () {
  60366. var subdivisionsX = this._subdivisionsX;
  60367. var subdivisionsY = this._subdivisionsY;
  60368. this._heightQuads = new Array();
  60369. for (var row = 0; row < subdivisionsY; row++) {
  60370. for (var col = 0; col < subdivisionsX; col++) {
  60371. 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) };
  60372. this._heightQuads[row * subdivisionsX + col] = quad;
  60373. }
  60374. }
  60375. return this;
  60376. };
  60377. // Compute each quad element values and update the the heightMap array :
  60378. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60379. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60380. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60381. // Returns the GroundMesh.
  60382. GroundMesh.prototype._computeHeightQuads = function () {
  60383. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60384. if (!positions) {
  60385. return this;
  60386. }
  60387. var v1 = BABYLON.Tmp.Vector3[3];
  60388. var v2 = BABYLON.Tmp.Vector3[2];
  60389. var v3 = BABYLON.Tmp.Vector3[1];
  60390. var v4 = BABYLON.Tmp.Vector3[0];
  60391. var v1v2 = BABYLON.Tmp.Vector3[4];
  60392. var v1v3 = BABYLON.Tmp.Vector3[5];
  60393. var v1v4 = BABYLON.Tmp.Vector3[6];
  60394. var norm1 = BABYLON.Tmp.Vector3[7];
  60395. var norm2 = BABYLON.Tmp.Vector3[8];
  60396. var i = 0;
  60397. var j = 0;
  60398. var k = 0;
  60399. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60400. var h = 0;
  60401. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60402. var d2 = 0;
  60403. var subdivisionsX = this._subdivisionsX;
  60404. var subdivisionsY = this._subdivisionsY;
  60405. for (var row = 0; row < subdivisionsY; row++) {
  60406. for (var col = 0; col < subdivisionsX; col++) {
  60407. i = col * 3;
  60408. j = row * (subdivisionsX + 1) * 3;
  60409. k = (row + 1) * (subdivisionsX + 1) * 3;
  60410. v1.x = positions[j + i];
  60411. v1.y = positions[j + i + 1];
  60412. v1.z = positions[j + i + 2];
  60413. v2.x = positions[j + i + 3];
  60414. v2.y = positions[j + i + 4];
  60415. v2.z = positions[j + i + 5];
  60416. v3.x = positions[k + i];
  60417. v3.y = positions[k + i + 1];
  60418. v3.z = positions[k + i + 2];
  60419. v4.x = positions[k + i + 3];
  60420. v4.y = positions[k + i + 4];
  60421. v4.z = positions[k + i + 5];
  60422. // 2D slope V1V4
  60423. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60424. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60425. // facet equations :
  60426. // we compute each facet normal vector
  60427. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60428. // we compute the value d by applying the equation to v1 which belongs to the plane
  60429. // then we store the facet equation in a Vector4
  60430. v2.subtractToRef(v1, v1v2);
  60431. v3.subtractToRef(v1, v1v3);
  60432. v4.subtractToRef(v1, v1v4);
  60433. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60434. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60435. norm1.normalize();
  60436. norm2.normalize();
  60437. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60438. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60439. var quad = this._heightQuads[row * subdivisionsX + col];
  60440. quad.slope.copyFromFloats(cd, h);
  60441. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60442. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60443. }
  60444. }
  60445. return this;
  60446. };
  60447. GroundMesh.prototype.serialize = function (serializationObject) {
  60448. _super.prototype.serialize.call(this, serializationObject);
  60449. serializationObject.subdivisionsX = this._subdivisionsX;
  60450. serializationObject.subdivisionsY = this._subdivisionsY;
  60451. serializationObject.minX = this._minX;
  60452. serializationObject.maxX = this._maxX;
  60453. serializationObject.minZ = this._minZ;
  60454. serializationObject.maxZ = this._maxZ;
  60455. serializationObject.width = this._width;
  60456. serializationObject.height = this._height;
  60457. };
  60458. GroundMesh.Parse = function (parsedMesh, scene) {
  60459. var result = new GroundMesh(parsedMesh.name, scene);
  60460. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60461. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60462. result._minX = parsedMesh.minX;
  60463. result._maxX = parsedMesh.maxX;
  60464. result._minZ = parsedMesh.minZ;
  60465. result._maxZ = parsedMesh.maxZ;
  60466. result._width = parsedMesh.width;
  60467. result._height = parsedMesh.height;
  60468. return result;
  60469. };
  60470. return GroundMesh;
  60471. }(BABYLON.Mesh));
  60472. BABYLON.GroundMesh = GroundMesh;
  60473. })(BABYLON || (BABYLON = {}));
  60474. //# sourceMappingURL=babylon.groundMesh.js.map
  60475. var BABYLON;
  60476. (function (BABYLON) {
  60477. /**
  60478. * Creates an instance based on a source mesh.
  60479. */
  60480. var InstancedMesh = /** @class */ (function (_super) {
  60481. __extends(InstancedMesh, _super);
  60482. function InstancedMesh(name, source) {
  60483. var _this = _super.call(this, name, source.getScene()) || this;
  60484. source.instances.push(_this);
  60485. _this._sourceMesh = source;
  60486. _this.position.copyFrom(source.position);
  60487. _this.rotation.copyFrom(source.rotation);
  60488. _this.scaling.copyFrom(source.scaling);
  60489. if (source.rotationQuaternion) {
  60490. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60491. }
  60492. _this.infiniteDistance = source.infiniteDistance;
  60493. _this.setPivotMatrix(source.getPivotMatrix());
  60494. _this.refreshBoundingInfo();
  60495. _this._syncSubMeshes();
  60496. return _this;
  60497. }
  60498. /**
  60499. * Returns the string "InstancedMesh".
  60500. */
  60501. InstancedMesh.prototype.getClassName = function () {
  60502. return "InstancedMesh";
  60503. };
  60504. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60505. // Methods
  60506. get: function () {
  60507. return this._sourceMesh.receiveShadows;
  60508. },
  60509. enumerable: true,
  60510. configurable: true
  60511. });
  60512. Object.defineProperty(InstancedMesh.prototype, "material", {
  60513. get: function () {
  60514. return this._sourceMesh.material;
  60515. },
  60516. enumerable: true,
  60517. configurable: true
  60518. });
  60519. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60520. get: function () {
  60521. return this._sourceMesh.visibility;
  60522. },
  60523. enumerable: true,
  60524. configurable: true
  60525. });
  60526. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60527. get: function () {
  60528. return this._sourceMesh.skeleton;
  60529. },
  60530. enumerable: true,
  60531. configurable: true
  60532. });
  60533. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60534. get: function () {
  60535. return this._sourceMesh.renderingGroupId;
  60536. },
  60537. set: function (value) {
  60538. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60539. return;
  60540. }
  60541. //no-op with warning
  60542. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60543. },
  60544. enumerable: true,
  60545. configurable: true
  60546. });
  60547. /**
  60548. * Returns the total number of vertices (integer).
  60549. */
  60550. InstancedMesh.prototype.getTotalVertices = function () {
  60551. return this._sourceMesh.getTotalVertices();
  60552. };
  60553. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60554. get: function () {
  60555. return this._sourceMesh;
  60556. },
  60557. enumerable: true,
  60558. configurable: true
  60559. });
  60560. /**
  60561. * Is this node ready to be used/rendered
  60562. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60563. * @return {boolean} is it ready
  60564. */
  60565. InstancedMesh.prototype.isReady = function (completeCheck) {
  60566. if (completeCheck === void 0) { completeCheck = false; }
  60567. return this._sourceMesh.isReady(completeCheck, true);
  60568. };
  60569. /**
  60570. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60571. */
  60572. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60573. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60574. };
  60575. /**
  60576. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60577. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60578. * The `data` are either a numeric array either a Float32Array.
  60579. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60580. * 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).
  60581. * Note that a new underlying VertexBuffer object is created each call.
  60582. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60583. *
  60584. * Possible `kind` values :
  60585. * - BABYLON.VertexBuffer.PositionKind
  60586. * - BABYLON.VertexBuffer.UVKind
  60587. * - BABYLON.VertexBuffer.UV2Kind
  60588. * - BABYLON.VertexBuffer.UV3Kind
  60589. * - BABYLON.VertexBuffer.UV4Kind
  60590. * - BABYLON.VertexBuffer.UV5Kind
  60591. * - BABYLON.VertexBuffer.UV6Kind
  60592. * - BABYLON.VertexBuffer.ColorKind
  60593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60597. *
  60598. * Returns the Mesh.
  60599. */
  60600. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60601. if (this.sourceMesh) {
  60602. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60603. }
  60604. return this.sourceMesh;
  60605. };
  60606. /**
  60607. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60608. * If the mesh has no geometry, it is simply returned as it is.
  60609. * The `data` are either a numeric array either a Float32Array.
  60610. * No new underlying VertexBuffer object is created.
  60611. * 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.
  60612. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60613. *
  60614. * Possible `kind` values :
  60615. * - BABYLON.VertexBuffer.PositionKind
  60616. * - BABYLON.VertexBuffer.UVKind
  60617. * - BABYLON.VertexBuffer.UV2Kind
  60618. * - BABYLON.VertexBuffer.UV3Kind
  60619. * - BABYLON.VertexBuffer.UV4Kind
  60620. * - BABYLON.VertexBuffer.UV5Kind
  60621. * - BABYLON.VertexBuffer.UV6Kind
  60622. * - BABYLON.VertexBuffer.ColorKind
  60623. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60624. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60625. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60626. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60627. *
  60628. * Returns the Mesh.
  60629. */
  60630. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60631. if (this.sourceMesh) {
  60632. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60633. }
  60634. return this.sourceMesh;
  60635. };
  60636. /**
  60637. * Sets the mesh indices.
  60638. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60639. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60640. * This method creates a new index buffer each call.
  60641. * Returns the Mesh.
  60642. */
  60643. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60644. if (totalVertices === void 0) { totalVertices = null; }
  60645. if (this.sourceMesh) {
  60646. this.sourceMesh.setIndices(indices, totalVertices);
  60647. }
  60648. return this.sourceMesh;
  60649. };
  60650. /**
  60651. * Boolean : True if the mesh owns the requested kind of data.
  60652. */
  60653. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60654. return this._sourceMesh.isVerticesDataPresent(kind);
  60655. };
  60656. /**
  60657. * Returns an array of indices (IndicesArray).
  60658. */
  60659. InstancedMesh.prototype.getIndices = function () {
  60660. return this._sourceMesh.getIndices();
  60661. };
  60662. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60663. get: function () {
  60664. return this._sourceMesh._positions;
  60665. },
  60666. enumerable: true,
  60667. configurable: true
  60668. });
  60669. /**
  60670. * Sets a new updated BoundingInfo to the mesh.
  60671. * Returns the mesh.
  60672. */
  60673. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60674. var meshBB = this._sourceMesh.getBoundingInfo();
  60675. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60676. this._updateBoundingInfo();
  60677. return this;
  60678. };
  60679. InstancedMesh.prototype._preActivate = function () {
  60680. if (this._currentLOD) {
  60681. this._currentLOD._preActivate();
  60682. }
  60683. return this;
  60684. };
  60685. InstancedMesh.prototype._activate = function (renderId) {
  60686. if (this._currentLOD) {
  60687. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60688. }
  60689. return this;
  60690. };
  60691. /**
  60692. * Returns the current associated LOD AbstractMesh.
  60693. */
  60694. InstancedMesh.prototype.getLOD = function (camera) {
  60695. if (!camera) {
  60696. return this;
  60697. }
  60698. var boundingInfo = this.getBoundingInfo();
  60699. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60700. if (this._currentLOD === this.sourceMesh) {
  60701. return this;
  60702. }
  60703. return this._currentLOD;
  60704. };
  60705. InstancedMesh.prototype._syncSubMeshes = function () {
  60706. this.releaseSubMeshes();
  60707. if (this._sourceMesh.subMeshes) {
  60708. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60709. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60710. }
  60711. }
  60712. return this;
  60713. };
  60714. InstancedMesh.prototype._generatePointsArray = function () {
  60715. return this._sourceMesh._generatePointsArray();
  60716. };
  60717. /**
  60718. * Creates a new InstancedMesh from the current mesh.
  60719. * - name (string) : the cloned mesh name
  60720. * - newParent (optional Node) : the optional Node to parent the clone to.
  60721. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60722. *
  60723. * Returns the clone.
  60724. */
  60725. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60726. var result = this._sourceMesh.createInstance(name);
  60727. // Deep copy
  60728. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60729. // Bounding info
  60730. this.refreshBoundingInfo();
  60731. // Parent
  60732. if (newParent) {
  60733. result.parent = newParent;
  60734. }
  60735. if (!doNotCloneChildren) {
  60736. // Children
  60737. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60738. var mesh = this.getScene().meshes[index];
  60739. if (mesh.parent === this) {
  60740. mesh.clone(mesh.name, result);
  60741. }
  60742. }
  60743. }
  60744. result.computeWorldMatrix(true);
  60745. return result;
  60746. };
  60747. /**
  60748. * Disposes the InstancedMesh.
  60749. * Returns nothing.
  60750. */
  60751. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60752. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60753. // Remove from mesh
  60754. var index = this._sourceMesh.instances.indexOf(this);
  60755. this._sourceMesh.instances.splice(index, 1);
  60756. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60757. };
  60758. return InstancedMesh;
  60759. }(BABYLON.AbstractMesh));
  60760. BABYLON.InstancedMesh = InstancedMesh;
  60761. })(BABYLON || (BABYLON = {}));
  60762. //# sourceMappingURL=babylon.instancedMesh.js.map
  60763. var BABYLON;
  60764. (function (BABYLON) {
  60765. var LinesMesh = /** @class */ (function (_super) {
  60766. __extends(LinesMesh, _super);
  60767. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60768. if (scene === void 0) { scene = null; }
  60769. if (parent === void 0) { parent = null; }
  60770. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60771. _this.useVertexColor = useVertexColor;
  60772. _this.useVertexAlpha = useVertexAlpha;
  60773. _this.color = new BABYLON.Color3(1, 1, 1);
  60774. _this.alpha = 1;
  60775. if (source) {
  60776. _this.color = source.color.clone();
  60777. _this.alpha = source.alpha;
  60778. _this.useVertexColor = source.useVertexColor;
  60779. _this.useVertexAlpha = source.useVertexAlpha;
  60780. }
  60781. _this._intersectionThreshold = 0.1;
  60782. var defines = [];
  60783. var options = {
  60784. attributes: [BABYLON.VertexBuffer.PositionKind],
  60785. uniforms: ["world", "viewProjection"],
  60786. needAlphaBlending: true,
  60787. defines: defines
  60788. };
  60789. if (useVertexAlpha === false) {
  60790. options.needAlphaBlending = false;
  60791. }
  60792. if (!useVertexColor) {
  60793. options.uniforms.push("color");
  60794. }
  60795. else {
  60796. options.defines.push("#define VERTEXCOLOR");
  60797. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60798. }
  60799. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60800. return _this;
  60801. }
  60802. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60803. /**
  60804. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60805. * This margin is expressed in world space coordinates, so its value may vary.
  60806. * Default value is 0.1
  60807. * @returns the intersection Threshold value.
  60808. */
  60809. get: function () {
  60810. return this._intersectionThreshold;
  60811. },
  60812. /**
  60813. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60814. * This margin is expressed in world space coordinates, so its value may vary.
  60815. * @param value the new threshold to apply
  60816. */
  60817. set: function (value) {
  60818. if (this._intersectionThreshold === value) {
  60819. return;
  60820. }
  60821. this._intersectionThreshold = value;
  60822. if (this.geometry) {
  60823. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60824. }
  60825. },
  60826. enumerable: true,
  60827. configurable: true
  60828. });
  60829. /**
  60830. * Returns the string "LineMesh"
  60831. */
  60832. LinesMesh.prototype.getClassName = function () {
  60833. return "LinesMesh";
  60834. };
  60835. Object.defineProperty(LinesMesh.prototype, "material", {
  60836. get: function () {
  60837. return this._colorShader;
  60838. },
  60839. set: function (value) {
  60840. // Do nothing
  60841. },
  60842. enumerable: true,
  60843. configurable: true
  60844. });
  60845. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60846. get: function () {
  60847. return false;
  60848. },
  60849. enumerable: true,
  60850. configurable: true
  60851. });
  60852. LinesMesh.prototype.createInstance = function (name) {
  60853. throw new Error("LinesMeshes do not support createInstance.");
  60854. };
  60855. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60856. if (!this._geometry) {
  60857. return this;
  60858. }
  60859. // VBOs
  60860. this._geometry._bind(this._colorShader.getEffect());
  60861. // Color
  60862. if (!this.useVertexColor) {
  60863. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60864. }
  60865. return this;
  60866. };
  60867. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60868. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60869. return this;
  60870. }
  60871. var engine = this.getScene().getEngine();
  60872. // Draw order
  60873. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60874. return this;
  60875. };
  60876. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60877. this._colorShader.dispose();
  60878. _super.prototype.dispose.call(this, doNotRecurse);
  60879. };
  60880. /**
  60881. * Returns a new LineMesh object cloned from the current one.
  60882. */
  60883. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60884. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60885. };
  60886. return LinesMesh;
  60887. }(BABYLON.Mesh));
  60888. BABYLON.LinesMesh = LinesMesh;
  60889. })(BABYLON || (BABYLON = {}));
  60890. //# sourceMappingURL=babylon.linesMesh.js.map
  60891. var BABYLON;
  60892. (function (BABYLON) {
  60893. /**
  60894. * Class containing static functions to help procedurally build meshes
  60895. */
  60896. var MeshBuilder = /** @class */ (function () {
  60897. function MeshBuilder() {
  60898. }
  60899. MeshBuilder.updateSideOrientation = function (orientation) {
  60900. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60901. return BABYLON.Mesh.DOUBLESIDE;
  60902. }
  60903. if (orientation === undefined || orientation === null) {
  60904. return BABYLON.Mesh.FRONTSIDE;
  60905. }
  60906. return orientation;
  60907. };
  60908. /**
  60909. * Creates a box mesh
  60910. * * The parameter `size` sets the size (float) of each box side (default 1)
  60911. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60912. * * 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)
  60913. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60914. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60915. * * 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
  60916. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60917. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60918. * @param name defines the name of the mesh
  60919. * @param options defines the options used to create the mesh
  60920. * @param scene defines the hosting scene
  60921. * @returns the box mesh
  60922. */
  60923. MeshBuilder.CreateBox = function (name, options, scene) {
  60924. if (scene === void 0) { scene = null; }
  60925. var box = new BABYLON.Mesh(name, scene);
  60926. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60927. box._originalBuilderSideOrientation = options.sideOrientation;
  60928. var vertexData = BABYLON.VertexData.CreateBox(options);
  60929. vertexData.applyToMesh(box, options.updatable);
  60930. return box;
  60931. };
  60932. /**
  60933. * Creates a sphere mesh
  60934. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60935. * * 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`)
  60936. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60937. * * 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
  60938. * * 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)
  60939. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60940. * * 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
  60941. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60942. * @param name defines the name of the mesh
  60943. * @param options defines the options used to create the mesh
  60944. * @param scene defines the hosting scene
  60945. * @returns the sphere mesh
  60946. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60947. */
  60948. MeshBuilder.CreateSphere = function (name, options, scene) {
  60949. var sphere = new BABYLON.Mesh(name, scene);
  60950. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60951. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60952. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60953. vertexData.applyToMesh(sphere, options.updatable);
  60954. return sphere;
  60955. };
  60956. /**
  60957. * Creates a plane polygonal mesh. By default, this is a disc
  60958. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60959. * * 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
  60960. * * 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
  60961. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60962. * * 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
  60963. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60964. * @param name defines the name of the mesh
  60965. * @param options defines the options used to create the mesh
  60966. * @param scene defines the hosting scene
  60967. * @returns the plane polygonal mesh
  60968. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60969. */
  60970. MeshBuilder.CreateDisc = function (name, options, scene) {
  60971. if (scene === void 0) { scene = null; }
  60972. var disc = new BABYLON.Mesh(name, scene);
  60973. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60974. disc._originalBuilderSideOrientation = options.sideOrientation;
  60975. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60976. vertexData.applyToMesh(disc, options.updatable);
  60977. return disc;
  60978. };
  60979. /**
  60980. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60981. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60982. * * 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`)
  60983. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60984. * * 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
  60985. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60986. * * 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
  60987. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60988. * @param name defines the name of the mesh
  60989. * @param options defines the options used to create the mesh
  60990. * @param scene defines the hosting scene
  60991. * @returns the icosahedron mesh
  60992. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60993. */
  60994. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60995. var sphere = new BABYLON.Mesh(name, scene);
  60996. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60997. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60998. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60999. vertexData.applyToMesh(sphere, options.updatable);
  61000. return sphere;
  61001. };
  61002. ;
  61003. /**
  61004. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61005. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61006. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61007. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61008. * * 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
  61009. * * 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
  61010. * * 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
  61011. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61012. * * 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
  61013. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61014. * * 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
  61015. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61016. * * 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
  61017. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61018. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61019. * @param name defines the name of the mesh
  61020. * @param options defines the options used to create the mesh
  61021. * @param scene defines the hosting scene
  61022. * @returns the ribbon mesh
  61023. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61024. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61025. */
  61026. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61027. if (scene === void 0) { scene = null; }
  61028. var pathArray = options.pathArray;
  61029. var closeArray = options.closeArray;
  61030. var closePath = options.closePath;
  61031. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61032. var instance = options.instance;
  61033. var updatable = options.updatable;
  61034. if (instance) { // existing ribbon instance update
  61035. // positionFunction : ribbon case
  61036. // only pathArray and sideOrientation parameters are taken into account for positions update
  61037. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61038. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61039. var positionFunction = function (positions) {
  61040. var minlg = pathArray[0].length;
  61041. var i = 0;
  61042. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61043. for (var si = 1; si <= ns; si++) {
  61044. for (var p = 0; p < pathArray.length; p++) {
  61045. var path = pathArray[p];
  61046. var l = path.length;
  61047. minlg = (minlg < l) ? minlg : l;
  61048. var j = 0;
  61049. while (j < minlg) {
  61050. positions[i] = path[j].x;
  61051. positions[i + 1] = path[j].y;
  61052. positions[i + 2] = path[j].z;
  61053. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61054. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61055. }
  61056. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61057. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61058. }
  61059. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61060. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61061. }
  61062. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61063. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61064. }
  61065. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61066. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61067. }
  61068. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61069. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61070. }
  61071. j++;
  61072. i += 3;
  61073. }
  61074. if (instance._closePath) {
  61075. positions[i] = path[0].x;
  61076. positions[i + 1] = path[0].y;
  61077. positions[i + 2] = path[0].z;
  61078. i += 3;
  61079. }
  61080. }
  61081. }
  61082. };
  61083. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61084. positionFunction(positions);
  61085. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61086. instance._boundingInfo.update(instance._worldMatrix);
  61087. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61088. if (options.colors) {
  61089. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61090. for (var c = 0; c < options.colors.length; c++) {
  61091. colors[c * 4] = options.colors[c].r;
  61092. colors[c * 4 + 1] = options.colors[c].g;
  61093. colors[c * 4 + 2] = options.colors[c].b;
  61094. colors[c * 4 + 3] = options.colors[c].a;
  61095. }
  61096. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61097. }
  61098. if (options.uvs) {
  61099. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61100. for (var i = 0; i < options.uvs.length; i++) {
  61101. uvs[i * 2] = options.uvs[i].x;
  61102. uvs[i * 2 + 1] = options.uvs[i].y;
  61103. }
  61104. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61105. }
  61106. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61107. var indices = instance.getIndices();
  61108. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61109. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61110. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61111. if (instance._closePath) {
  61112. var indexFirst = 0;
  61113. var indexLast = 0;
  61114. for (var p = 0; p < pathArray.length; p++) {
  61115. indexFirst = instance._idx[p] * 3;
  61116. if (p + 1 < pathArray.length) {
  61117. indexLast = (instance._idx[p + 1] - 1) * 3;
  61118. }
  61119. else {
  61120. indexLast = normals.length - 3;
  61121. }
  61122. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61123. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61124. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61125. normals[indexLast] = normals[indexFirst];
  61126. normals[indexLast + 1] = normals[indexFirst + 1];
  61127. normals[indexLast + 2] = normals[indexFirst + 2];
  61128. }
  61129. }
  61130. if (!(instance.areNormalsFrozen)) {
  61131. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61132. }
  61133. }
  61134. return instance;
  61135. }
  61136. else { // new ribbon creation
  61137. var ribbon = new BABYLON.Mesh(name, scene);
  61138. ribbon._originalBuilderSideOrientation = sideOrientation;
  61139. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61140. if (closePath) {
  61141. ribbon._idx = vertexData._idx;
  61142. }
  61143. ribbon._closePath = closePath;
  61144. ribbon._closeArray = closeArray;
  61145. vertexData.applyToMesh(ribbon, updatable);
  61146. return ribbon;
  61147. }
  61148. };
  61149. /**
  61150. * Creates a cylinder or a cone mesh
  61151. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61152. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61153. * * 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.
  61154. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61155. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61156. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61157. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61158. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61159. * * 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).
  61160. * * 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
  61161. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61162. * * 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
  61163. * * 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.
  61164. * * If `enclose` is false, a ring surface is one element.
  61165. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61166. * * 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
  61167. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61168. * * 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
  61169. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61170. * @param name defines the name of the mesh
  61171. * @param options defines the options used to create the mesh
  61172. * @param scene defines the hosting scene
  61173. * @returns the cylinder mesh
  61174. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61175. */
  61176. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61177. var cylinder = new BABYLON.Mesh(name, scene);
  61178. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61179. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61180. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61181. vertexData.applyToMesh(cylinder, options.updatable);
  61182. return cylinder;
  61183. };
  61184. /**
  61185. * Creates a torus mesh
  61186. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61187. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61188. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61189. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61190. * * 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
  61191. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61192. * @param name defines the name of the mesh
  61193. * @param options defines the options used to create the mesh
  61194. * @param scene defines the hosting scene
  61195. * @returns the torus mesh
  61196. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61197. */
  61198. MeshBuilder.CreateTorus = function (name, options, scene) {
  61199. var torus = new BABYLON.Mesh(name, scene);
  61200. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61201. torus._originalBuilderSideOrientation = options.sideOrientation;
  61202. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61203. vertexData.applyToMesh(torus, options.updatable);
  61204. return torus;
  61205. };
  61206. /**
  61207. * Creates a torus knot mesh
  61208. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61209. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61210. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61211. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61212. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61213. * * 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
  61214. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61215. * @param name defines the name of the mesh
  61216. * @param options defines the options used to create the mesh
  61217. * @param scene defines the hosting scene
  61218. * @returns the torus knot mesh
  61219. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61220. */
  61221. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61222. var torusKnot = new BABYLON.Mesh(name, scene);
  61223. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61224. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61225. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61226. vertexData.applyToMesh(torusKnot, options.updatable);
  61227. return torusKnot;
  61228. };
  61229. /**
  61230. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61231. * * 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
  61232. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61233. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61234. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61235. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61236. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61237. * * 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
  61238. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61239. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61240. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61241. * @param name defines the name of the new line system
  61242. * @param options defines the options used to create the line system
  61243. * @param scene defines the hosting scene
  61244. * @returns a new line system mesh
  61245. */
  61246. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61247. var instance = options.instance;
  61248. var lines = options.lines;
  61249. var colors = options.colors;
  61250. if (instance) { // lines update
  61251. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61252. var vertexColor;
  61253. var lineColors;
  61254. if (colors) {
  61255. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61256. }
  61257. var i = 0;
  61258. var c = 0;
  61259. for (var l = 0; l < lines.length; l++) {
  61260. var points = lines[l];
  61261. for (var p = 0; p < points.length; p++) {
  61262. positions[i] = points[p].x;
  61263. positions[i + 1] = points[p].y;
  61264. positions[i + 2] = points[p].z;
  61265. if (colors && vertexColor) {
  61266. lineColors = colors[l];
  61267. vertexColor[c] = lineColors[p].r;
  61268. vertexColor[c + 1] = lineColors[p].g;
  61269. vertexColor[c + 2] = lineColors[p].b;
  61270. vertexColor[c + 3] = lineColors[p].a;
  61271. c += 4;
  61272. }
  61273. i += 3;
  61274. }
  61275. }
  61276. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61277. if (colors && vertexColor) {
  61278. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61279. }
  61280. return instance;
  61281. }
  61282. // line system creation
  61283. var useVertexColor = (colors) ? true : false;
  61284. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61285. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61286. vertexData.applyToMesh(lineSystem, options.updatable);
  61287. return lineSystem;
  61288. };
  61289. /**
  61290. * Creates a line mesh
  61291. * 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
  61292. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61293. * * The parameter `points` is an array successive Vector3
  61294. * * 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
  61295. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61296. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61297. * * When updating an instance, remember that only point positions can change, not the number of points
  61298. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61299. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61300. * @param name defines the name of the new line system
  61301. * @param options defines the options used to create the line system
  61302. * @param scene defines the hosting scene
  61303. * @returns a new line mesh
  61304. */
  61305. MeshBuilder.CreateLines = function (name, options, scene) {
  61306. if (scene === void 0) { scene = null; }
  61307. var colors = (options.colors) ? [options.colors] : null;
  61308. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61309. return lines;
  61310. };
  61311. /**
  61312. * Creates a dashed line mesh
  61313. * * 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
  61314. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61315. * * The parameter `points` is an array successive Vector3
  61316. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61317. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61318. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61319. * * 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
  61320. * * When updating an instance, remember that only point positions can change, not the number of points
  61321. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61322. * @param name defines the name of the mesh
  61323. * @param options defines the options used to create the mesh
  61324. * @param scene defines the hosting scene
  61325. * @returns the dashed line mesh
  61326. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61327. */
  61328. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61329. if (scene === void 0) { scene = null; }
  61330. var points = options.points;
  61331. var instance = options.instance;
  61332. var gapSize = options.gapSize || 1;
  61333. var dashSize = options.dashSize || 3;
  61334. if (instance) { // dashed lines update
  61335. var positionFunction = function (positions) {
  61336. var curvect = BABYLON.Vector3.Zero();
  61337. var nbSeg = positions.length / 6;
  61338. var lg = 0;
  61339. var nb = 0;
  61340. var shft = 0;
  61341. var dashshft = 0;
  61342. var curshft = 0;
  61343. var p = 0;
  61344. var i = 0;
  61345. var j = 0;
  61346. for (i = 0; i < points.length - 1; i++) {
  61347. points[i + 1].subtractToRef(points[i], curvect);
  61348. lg += curvect.length();
  61349. }
  61350. shft = lg / nbSeg;
  61351. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61352. for (i = 0; i < points.length - 1; i++) {
  61353. points[i + 1].subtractToRef(points[i], curvect);
  61354. nb = Math.floor(curvect.length() / shft);
  61355. curvect.normalize();
  61356. j = 0;
  61357. while (j < nb && p < positions.length) {
  61358. curshft = shft * j;
  61359. positions[p] = points[i].x + curshft * curvect.x;
  61360. positions[p + 1] = points[i].y + curshft * curvect.y;
  61361. positions[p + 2] = points[i].z + curshft * curvect.z;
  61362. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61363. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61364. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61365. p += 6;
  61366. j++;
  61367. }
  61368. }
  61369. while (p < positions.length) {
  61370. positions[p] = points[i].x;
  61371. positions[p + 1] = points[i].y;
  61372. positions[p + 2] = points[i].z;
  61373. p += 3;
  61374. }
  61375. };
  61376. instance.updateMeshPositions(positionFunction, false);
  61377. return instance;
  61378. }
  61379. // dashed lines creation
  61380. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61381. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61382. vertexData.applyToMesh(dashedLines, options.updatable);
  61383. dashedLines.dashSize = dashSize;
  61384. dashedLines.gapSize = gapSize;
  61385. return dashedLines;
  61386. };
  61387. /**
  61388. * 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.
  61389. * * 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.
  61390. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61391. * * 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.
  61392. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61393. * * 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
  61394. * * 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
  61395. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61396. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61397. * * 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
  61398. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61399. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61400. * @param name defines the name of the mesh
  61401. * @param options defines the options used to create the mesh
  61402. * @param scene defines the hosting scene
  61403. * @returns the extruded shape mesh
  61404. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61405. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61406. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61407. */
  61408. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61409. if (scene === void 0) { scene = null; }
  61410. var path = options.path;
  61411. var shape = options.shape;
  61412. var scale = options.scale || 1;
  61413. var rotation = options.rotation || 0;
  61414. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61415. var updatable = options.updatable;
  61416. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61417. var instance = options.instance || null;
  61418. var invertUV = options.invertUV || false;
  61419. 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);
  61420. };
  61421. /**
  61422. * Creates an custom extruded shape mesh.
  61423. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61424. * * 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.
  61425. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61426. * * 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
  61427. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61428. * * 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
  61429. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61430. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61431. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61432. * * 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
  61433. * * 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
  61434. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61435. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61436. * * 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
  61437. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61438. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61439. * @param name defines the name of the mesh
  61440. * @param options defines the options used to create the mesh
  61441. * @param scene defines the hosting scene
  61442. * @returns the custom extruded shape mesh
  61443. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61444. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61445. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61446. */
  61447. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61448. var path = options.path;
  61449. var shape = options.shape;
  61450. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61451. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61452. var ribbonCloseArray = options.ribbonCloseArray || false;
  61453. var ribbonClosePath = options.ribbonClosePath || false;
  61454. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61455. var updatable = options.updatable;
  61456. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61457. var instance = options.instance;
  61458. var invertUV = options.invertUV || false;
  61459. 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);
  61460. };
  61461. /**
  61462. * Creates lathe mesh.
  61463. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61464. * * 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
  61465. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61466. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61467. * * 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
  61468. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61469. * * 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
  61470. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61471. * * 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
  61472. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61473. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61474. * @param name defines the name of the mesh
  61475. * @param options defines the options used to create the mesh
  61476. * @param scene defines the hosting scene
  61477. * @returns the lathe mesh
  61478. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61479. */
  61480. MeshBuilder.CreateLathe = function (name, options, scene) {
  61481. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61482. var closed = (options.closed === undefined) ? true : options.closed;
  61483. var shape = options.shape;
  61484. var radius = options.radius || 1;
  61485. var tessellation = options.tessellation || 64;
  61486. var updatable = options.updatable;
  61487. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61488. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61489. var pi2 = Math.PI * 2;
  61490. var paths = new Array();
  61491. var invertUV = options.invertUV || false;
  61492. var i = 0;
  61493. var p = 0;
  61494. var step = pi2 / tessellation * arc;
  61495. var rotated;
  61496. var path = new Array();
  61497. for (i = 0; i <= tessellation; i++) {
  61498. var path = [];
  61499. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61500. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61501. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61502. }
  61503. for (p = 0; p < shape.length; p++) {
  61504. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61505. path.push(rotated);
  61506. }
  61507. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61508. 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));
  61509. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61510. }
  61511. paths.push(path);
  61512. }
  61513. // lathe ribbon
  61514. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61515. return lathe;
  61516. };
  61517. /**
  61518. * Creates a plane mesh
  61519. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61520. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61521. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61522. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61523. * * 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
  61524. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61525. * @param name defines the name of the mesh
  61526. * @param options defines the options used to create the mesh
  61527. * @param scene defines the hosting scene
  61528. * @returns the plane mesh
  61529. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61530. */
  61531. MeshBuilder.CreatePlane = function (name, options, scene) {
  61532. var plane = new BABYLON.Mesh(name, scene);
  61533. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61534. plane._originalBuilderSideOrientation = options.sideOrientation;
  61535. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61536. vertexData.applyToMesh(plane, options.updatable);
  61537. if (options.sourcePlane) {
  61538. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61539. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61540. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61541. plane.rotate(vectorProduct, product);
  61542. }
  61543. return plane;
  61544. };
  61545. /**
  61546. * Creates a ground mesh
  61547. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61548. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61549. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61550. * @param name defines the name of the mesh
  61551. * @param options defines the options used to create the mesh
  61552. * @param scene defines the hosting scene
  61553. * @returns the ground mesh
  61554. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61555. */
  61556. MeshBuilder.CreateGround = function (name, options, scene) {
  61557. var ground = new BABYLON.GroundMesh(name, scene);
  61558. ground._setReady(false);
  61559. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61560. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61561. ground._width = options.width || 1;
  61562. ground._height = options.height || 1;
  61563. ground._maxX = ground._width / 2;
  61564. ground._maxZ = ground._height / 2;
  61565. ground._minX = -ground._maxX;
  61566. ground._minZ = -ground._maxZ;
  61567. var vertexData = BABYLON.VertexData.CreateGround(options);
  61568. vertexData.applyToMesh(ground, options.updatable);
  61569. ground._setReady(true);
  61570. return ground;
  61571. };
  61572. /**
  61573. * Creates a tiled ground mesh
  61574. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61575. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61576. * * 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
  61577. * * 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
  61578. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61579. * @param name defines the name of the mesh
  61580. * @param options defines the options used to create the mesh
  61581. * @param scene defines the hosting scene
  61582. * @returns the tiled ground mesh
  61583. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61584. */
  61585. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61586. var tiledGround = new BABYLON.Mesh(name, scene);
  61587. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61588. vertexData.applyToMesh(tiledGround, options.updatable);
  61589. return tiledGround;
  61590. };
  61591. /**
  61592. * Creates a ground mesh from a height map
  61593. * * The parameter `url` sets the URL of the height map image resource.
  61594. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61595. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61596. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61597. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61598. * * 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.
  61599. * * 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).
  61600. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61601. * @param name defines the name of the mesh
  61602. * @param url defines the url to the height map
  61603. * @param options defines the options used to create the mesh
  61604. * @param scene defines the hosting scene
  61605. * @returns the ground mesh
  61606. * @see http://doc.babylonjs.com/babylon101/height_map
  61607. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61608. */
  61609. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61610. var width = options.width || 10.0;
  61611. var height = options.height || 10.0;
  61612. var subdivisions = options.subdivisions || 1 | 0;
  61613. var minHeight = options.minHeight || 0.0;
  61614. var maxHeight = options.maxHeight || 1.0;
  61615. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61616. var updatable = options.updatable;
  61617. var onReady = options.onReady;
  61618. var ground = new BABYLON.GroundMesh(name, scene);
  61619. ground._subdivisionsX = subdivisions;
  61620. ground._subdivisionsY = subdivisions;
  61621. ground._width = width;
  61622. ground._height = height;
  61623. ground._maxX = ground._width / 2.0;
  61624. ground._maxZ = ground._height / 2.0;
  61625. ground._minX = -ground._maxX;
  61626. ground._minZ = -ground._maxZ;
  61627. ground._setReady(false);
  61628. var onload = function (img) {
  61629. // Getting height map data
  61630. var canvas = document.createElement("canvas");
  61631. var context = canvas.getContext("2d");
  61632. if (!context) {
  61633. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61634. }
  61635. if (scene.isDisposed) {
  61636. return;
  61637. }
  61638. var bufferWidth = img.width;
  61639. var bufferHeight = img.height;
  61640. canvas.width = bufferWidth;
  61641. canvas.height = bufferHeight;
  61642. context.drawImage(img, 0, 0);
  61643. // Create VertexData from map data
  61644. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61645. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61646. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61647. width: width, height: height,
  61648. subdivisions: subdivisions,
  61649. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61650. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61651. });
  61652. vertexData.applyToMesh(ground, updatable);
  61653. //execute ready callback, if set
  61654. if (onReady) {
  61655. onReady(ground);
  61656. }
  61657. ground._setReady(true);
  61658. };
  61659. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61660. return ground;
  61661. };
  61662. /**
  61663. * Creates a polygon mesh
  61664. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61665. * * 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
  61666. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61668. * * 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)
  61669. * * Remember you can only change the shape positions, not their number when updating a polygon
  61670. * @param name defines the name of the mesh
  61671. * @param options defines the options used to create the mesh
  61672. * @param scene defines the hosting scene
  61673. * @returns the polygon mesh
  61674. */
  61675. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61676. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61677. var shape = options.shape;
  61678. var holes = options.holes || [];
  61679. var depth = options.depth || 0;
  61680. var contours = [];
  61681. var hole = [];
  61682. for (var i = 0; i < shape.length; i++) {
  61683. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61684. }
  61685. var epsilon = 0.00000001;
  61686. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61687. contours.pop();
  61688. }
  61689. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61690. for (var hNb = 0; hNb < holes.length; hNb++) {
  61691. hole = [];
  61692. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61693. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61694. }
  61695. polygonTriangulation.addHole(hole);
  61696. }
  61697. var polygon = polygonTriangulation.build(options.updatable, depth);
  61698. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61699. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61700. vertexData.applyToMesh(polygon, options.updatable);
  61701. return polygon;
  61702. };
  61703. ;
  61704. /**
  61705. * Creates an extruded polygon mesh, with depth in the Y direction.
  61706. * * 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)
  61707. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61708. * @param name defines the name of the mesh
  61709. * @param options defines the options used to create the mesh
  61710. * @param scene defines the hosting scene
  61711. * @returns the polygon mesh
  61712. */
  61713. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61714. return MeshBuilder.CreatePolygon(name, options, scene);
  61715. };
  61716. ;
  61717. /**
  61718. * Creates a tube mesh.
  61719. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61720. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61721. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61722. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61723. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61724. * * 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)
  61725. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61726. * * 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
  61727. * * 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
  61728. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61729. * * 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
  61730. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61731. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61732. * @param name defines the name of the mesh
  61733. * @param options defines the options used to create the mesh
  61734. * @param scene defines the hosting scene
  61735. * @returns the tube mesh
  61736. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61737. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61738. */
  61739. MeshBuilder.CreateTube = function (name, options, scene) {
  61740. var path = options.path;
  61741. var instance = options.instance;
  61742. var radius = 1.0;
  61743. if (instance) {
  61744. radius = instance.radius;
  61745. }
  61746. if (options.radius !== undefined) {
  61747. radius = options.radius;
  61748. }
  61749. ;
  61750. var tessellation = options.tessellation || 64 | 0;
  61751. var radiusFunction = options.radiusFunction || null;
  61752. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61753. var invertUV = options.invertUV || false;
  61754. var updatable = options.updatable;
  61755. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61756. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61757. // tube geometry
  61758. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61759. var tangents = path3D.getTangents();
  61760. var normals = path3D.getNormals();
  61761. var distances = path3D.getDistances();
  61762. var pi2 = Math.PI * 2;
  61763. var step = pi2 / tessellation * arc;
  61764. var returnRadius = function () { return radius; };
  61765. var radiusFunctionFinal = radiusFunction || returnRadius;
  61766. var circlePath;
  61767. var rad;
  61768. var normal;
  61769. var rotated;
  61770. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61771. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61772. for (var i = 0; i < path.length; i++) {
  61773. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61774. circlePath = Array(); // current circle array
  61775. normal = normals[i]; // current normal
  61776. for (var t = 0; t < tessellation; t++) {
  61777. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61778. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61779. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61780. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61781. circlePath[t] = rotated;
  61782. }
  61783. circlePaths[index] = circlePath;
  61784. index++;
  61785. }
  61786. // cap
  61787. var capPath = function (nbPoints, pathIndex) {
  61788. var pointCap = Array();
  61789. for (var i = 0; i < nbPoints; i++) {
  61790. pointCap.push(path[pathIndex]);
  61791. }
  61792. return pointCap;
  61793. };
  61794. switch (cap) {
  61795. case BABYLON.Mesh.NO_CAP:
  61796. break;
  61797. case BABYLON.Mesh.CAP_START:
  61798. circlePaths[0] = capPath(tessellation, 0);
  61799. circlePaths[1] = circlePaths[2].slice(0);
  61800. break;
  61801. case BABYLON.Mesh.CAP_END:
  61802. circlePaths[index] = circlePaths[index - 1].slice(0);
  61803. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61804. break;
  61805. case BABYLON.Mesh.CAP_ALL:
  61806. circlePaths[0] = capPath(tessellation, 0);
  61807. circlePaths[1] = circlePaths[2].slice(0);
  61808. circlePaths[index] = circlePaths[index - 1].slice(0);
  61809. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61810. break;
  61811. default:
  61812. break;
  61813. }
  61814. return circlePaths;
  61815. };
  61816. var path3D;
  61817. var pathArray;
  61818. if (instance) { // tube update
  61819. var arc = options.arc || instance.arc;
  61820. path3D = (instance.path3D).update(path);
  61821. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61822. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61823. instance.path3D = path3D;
  61824. instance.pathArray = pathArray;
  61825. instance.arc = arc;
  61826. instance.radius = radius;
  61827. return instance;
  61828. }
  61829. // tube creation
  61830. path3D = new BABYLON.Path3D(path);
  61831. var newPathArray = new Array();
  61832. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61833. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61834. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61835. tube.pathArray = pathArray;
  61836. tube.path3D = path3D;
  61837. tube.tessellation = tessellation;
  61838. tube.cap = cap;
  61839. tube.arc = options.arc;
  61840. tube.radius = radius;
  61841. return tube;
  61842. };
  61843. /**
  61844. * Creates a polyhedron mesh
  61845. * * 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
  61846. * * The parameter `size` (positive float, default 1) sets the polygon size
  61847. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61848. * * 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`
  61849. * * 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
  61850. * * 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)`)
  61851. * * 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
  61852. * * 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
  61853. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61854. * * 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
  61855. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61856. * @param name defines the name of the mesh
  61857. * @param options defines the options used to create the mesh
  61858. * @param scene defines the hosting scene
  61859. * @returns the polyhedron mesh
  61860. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61861. */
  61862. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61863. var polyhedron = new BABYLON.Mesh(name, scene);
  61864. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61865. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61866. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61867. vertexData.applyToMesh(polyhedron, options.updatable);
  61868. return polyhedron;
  61869. };
  61870. /**
  61871. * Creates a decal mesh.
  61872. * 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
  61873. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61874. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61875. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61876. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61877. * @param name defines the name of the mesh
  61878. * @param sourceMesh defines the mesh where the decal must be applied
  61879. * @param options defines the options used to create the mesh
  61880. * @param scene defines the hosting scene
  61881. * @returns the decal mesh
  61882. * @see http://doc.babylonjs.com/how_to/decals
  61883. */
  61884. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61885. var indices = sourceMesh.getIndices();
  61886. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61887. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61888. var position = options.position || BABYLON.Vector3.Zero();
  61889. var normal = options.normal || BABYLON.Vector3.Up();
  61890. var size = options.size || BABYLON.Vector3.One();
  61891. var angle = options.angle || 0;
  61892. // Getting correct rotation
  61893. if (!normal) {
  61894. var target = new BABYLON.Vector3(0, 0, 1);
  61895. var camera = sourceMesh.getScene().activeCamera;
  61896. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61897. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61898. }
  61899. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61900. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61901. var pitch = Math.atan2(normal.y, len);
  61902. // Matrix
  61903. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61904. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61905. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61906. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61907. var vertexData = new BABYLON.VertexData();
  61908. vertexData.indices = [];
  61909. vertexData.positions = [];
  61910. vertexData.normals = [];
  61911. vertexData.uvs = [];
  61912. var currentVertexDataIndex = 0;
  61913. var extractDecalVector3 = function (indexId) {
  61914. var result = new BABYLON.PositionNormalVertex();
  61915. if (!indices || !positions || !normals) {
  61916. return result;
  61917. }
  61918. var vertexId = indices[indexId];
  61919. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61920. // Send vector to decal local world
  61921. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61922. // Get normal
  61923. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61924. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61925. return result;
  61926. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61927. var clip = function (vertices, axis) {
  61928. if (vertices.length === 0) {
  61929. return vertices;
  61930. }
  61931. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61932. var clipVertices = function (v0, v1) {
  61933. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61934. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61935. };
  61936. var result = new Array();
  61937. for (var index = 0; index < vertices.length; index += 3) {
  61938. var v1Out;
  61939. var v2Out;
  61940. var v3Out;
  61941. var total = 0;
  61942. var nV1 = null;
  61943. var nV2 = null;
  61944. var nV3 = null;
  61945. var nV4 = null;
  61946. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61947. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61948. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61949. v1Out = d1 > 0;
  61950. v2Out = d2 > 0;
  61951. v3Out = d3 > 0;
  61952. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61953. switch (total) {
  61954. case 0:
  61955. result.push(vertices[index]);
  61956. result.push(vertices[index + 1]);
  61957. result.push(vertices[index + 2]);
  61958. break;
  61959. case 1:
  61960. if (v1Out) {
  61961. nV1 = vertices[index + 1];
  61962. nV2 = vertices[index + 2];
  61963. nV3 = clipVertices(vertices[index], nV1);
  61964. nV4 = clipVertices(vertices[index], nV2);
  61965. }
  61966. if (v2Out) {
  61967. nV1 = vertices[index];
  61968. nV2 = vertices[index + 2];
  61969. nV3 = clipVertices(vertices[index + 1], nV1);
  61970. nV4 = clipVertices(vertices[index + 1], nV2);
  61971. result.push(nV3);
  61972. result.push(nV2.clone());
  61973. result.push(nV1.clone());
  61974. result.push(nV2.clone());
  61975. result.push(nV3.clone());
  61976. result.push(nV4);
  61977. break;
  61978. }
  61979. if (v3Out) {
  61980. nV1 = vertices[index];
  61981. nV2 = vertices[index + 1];
  61982. nV3 = clipVertices(vertices[index + 2], nV1);
  61983. nV4 = clipVertices(vertices[index + 2], nV2);
  61984. }
  61985. if (nV1 && nV2 && nV3 && nV4) {
  61986. result.push(nV1.clone());
  61987. result.push(nV2.clone());
  61988. result.push(nV3);
  61989. result.push(nV4);
  61990. result.push(nV3.clone());
  61991. result.push(nV2.clone());
  61992. }
  61993. break;
  61994. case 2:
  61995. if (!v1Out) {
  61996. nV1 = vertices[index].clone();
  61997. nV2 = clipVertices(nV1, vertices[index + 1]);
  61998. nV3 = clipVertices(nV1, vertices[index + 2]);
  61999. result.push(nV1);
  62000. result.push(nV2);
  62001. result.push(nV3);
  62002. }
  62003. if (!v2Out) {
  62004. nV1 = vertices[index + 1].clone();
  62005. nV2 = clipVertices(nV1, vertices[index + 2]);
  62006. nV3 = clipVertices(nV1, vertices[index]);
  62007. result.push(nV1);
  62008. result.push(nV2);
  62009. result.push(nV3);
  62010. }
  62011. if (!v3Out) {
  62012. nV1 = vertices[index + 2].clone();
  62013. nV2 = clipVertices(nV1, vertices[index]);
  62014. nV3 = clipVertices(nV1, vertices[index + 1]);
  62015. result.push(nV1);
  62016. result.push(nV2);
  62017. result.push(nV3);
  62018. }
  62019. break;
  62020. case 3:
  62021. break;
  62022. }
  62023. }
  62024. return result;
  62025. };
  62026. for (var index = 0; index < indices.length; index += 3) {
  62027. var faceVertices = new Array();
  62028. faceVertices.push(extractDecalVector3(index));
  62029. faceVertices.push(extractDecalVector3(index + 1));
  62030. faceVertices.push(extractDecalVector3(index + 2));
  62031. // Clip
  62032. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62033. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62034. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62035. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62036. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62037. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62038. if (faceVertices.length === 0) {
  62039. continue;
  62040. }
  62041. // Add UVs and get back to world
  62042. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62043. var vertex = faceVertices[vIndex];
  62044. //TODO check for Int32Array | Uint32Array | Uint16Array
  62045. vertexData.indices.push(currentVertexDataIndex);
  62046. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62047. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62048. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62049. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62050. currentVertexDataIndex++;
  62051. }
  62052. }
  62053. // Return mesh
  62054. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62055. vertexData.applyToMesh(decal);
  62056. decal.position = position.clone();
  62057. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62058. return decal;
  62059. };
  62060. // Privates
  62061. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62062. // extrusion geometry
  62063. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62064. var tangents = path3D.getTangents();
  62065. var normals = path3D.getNormals();
  62066. var binormals = path3D.getBinormals();
  62067. var distances = path3D.getDistances();
  62068. var angle = 0;
  62069. var returnScale = function () { return scale !== null ? scale : 1; };
  62070. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62071. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62072. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62073. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62074. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62075. for (var i = 0; i < curve.length; i++) {
  62076. var shapePath = new Array();
  62077. var angleStep = rotate(i, distances[i]);
  62078. var scaleRatio = scl(i, distances[i]);
  62079. for (var p = 0; p < shape.length; p++) {
  62080. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62081. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62082. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62083. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62084. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62085. shapePath[p] = rotated;
  62086. }
  62087. shapePaths[index] = shapePath;
  62088. angle += angleStep;
  62089. index++;
  62090. }
  62091. // cap
  62092. var capPath = function (shapePath) {
  62093. var pointCap = Array();
  62094. var barycenter = BABYLON.Vector3.Zero();
  62095. var i;
  62096. for (i = 0; i < shapePath.length; i++) {
  62097. barycenter.addInPlace(shapePath[i]);
  62098. }
  62099. barycenter.scaleInPlace(1.0 / shapePath.length);
  62100. for (i = 0; i < shapePath.length; i++) {
  62101. pointCap.push(barycenter);
  62102. }
  62103. return pointCap;
  62104. };
  62105. switch (cap) {
  62106. case BABYLON.Mesh.NO_CAP:
  62107. break;
  62108. case BABYLON.Mesh.CAP_START:
  62109. shapePaths[0] = capPath(shapePaths[2]);
  62110. shapePaths[1] = shapePaths[2];
  62111. break;
  62112. case BABYLON.Mesh.CAP_END:
  62113. shapePaths[index] = shapePaths[index - 1];
  62114. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62115. break;
  62116. case BABYLON.Mesh.CAP_ALL:
  62117. shapePaths[0] = capPath(shapePaths[2]);
  62118. shapePaths[1] = shapePaths[2];
  62119. shapePaths[index] = shapePaths[index - 1];
  62120. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62121. break;
  62122. default:
  62123. break;
  62124. }
  62125. return shapePaths;
  62126. };
  62127. var path3D;
  62128. var pathArray;
  62129. if (instance) { // instance update
  62130. path3D = (instance.path3D).update(curve);
  62131. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62132. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62133. return instance;
  62134. }
  62135. // extruded shape creation
  62136. path3D = new BABYLON.Path3D(curve);
  62137. var newShapePaths = new Array();
  62138. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62139. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62140. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62141. extrudedGeneric.pathArray = pathArray;
  62142. extrudedGeneric.path3D = path3D;
  62143. extrudedGeneric.cap = cap;
  62144. return extrudedGeneric;
  62145. };
  62146. return MeshBuilder;
  62147. }());
  62148. BABYLON.MeshBuilder = MeshBuilder;
  62149. })(BABYLON || (BABYLON = {}));
  62150. //# sourceMappingURL=babylon.meshBuilder.js.map
  62151. var BABYLON;
  62152. (function (BABYLON) {
  62153. /**
  62154. * Draco compression (https://google.github.io/draco/)
  62155. *
  62156. * This class wraps the Draco module.
  62157. *
  62158. * **Encoder**
  62159. *
  62160. * The encoder is not currently implemented.
  62161. *
  62162. * **Decoder**
  62163. *
  62164. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62165. *
  62166. * To update the configuration, use the following code:
  62167. * ```javascript
  62168. * BABYLON.DracoCompression.Configuration = {
  62169. * decoder: {
  62170. * wasmUrl: "<url to the WebAssembly library>",
  62171. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62172. * fallbackUrl: "<url to the fallback JavaScript library>",
  62173. * }
  62174. * };
  62175. * ```
  62176. *
  62177. * 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.
  62178. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62179. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62180. *
  62181. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62182. * ```javascript
  62183. * var dracoCompression = new BABYLON.DracoCompression();
  62184. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62185. * [BABYLON.VertexBuffer.PositionKind]: 0
  62186. * });
  62187. * ```
  62188. *
  62189. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62190. */
  62191. var DracoCompression = /** @class */ (function () {
  62192. /**
  62193. * Constructor
  62194. */
  62195. function DracoCompression() {
  62196. }
  62197. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62198. /**
  62199. * Returns true if the decoder is available.
  62200. */
  62201. get: function () {
  62202. if (typeof DracoDecoderModule !== "undefined") {
  62203. return true;
  62204. }
  62205. var decoder = DracoCompression.Configuration.decoder;
  62206. if (decoder) {
  62207. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62208. return true;
  62209. }
  62210. if (decoder.fallbackUrl) {
  62211. return true;
  62212. }
  62213. }
  62214. return false;
  62215. },
  62216. enumerable: true,
  62217. configurable: true
  62218. });
  62219. /**
  62220. * Stop all async operations and release resources.
  62221. */
  62222. DracoCompression.prototype.dispose = function () {
  62223. };
  62224. /**
  62225. * Decode Draco compressed mesh data to vertex data.
  62226. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62227. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62228. * @returns A promise that resolves with the decoded vertex data
  62229. */
  62230. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62231. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62232. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62233. var module = wrappedModule.module;
  62234. var vertexData = new BABYLON.VertexData();
  62235. var buffer = new module.DecoderBuffer();
  62236. buffer.Init(dataView, dataView.byteLength);
  62237. var decoder = new module.Decoder();
  62238. var geometry;
  62239. var status;
  62240. try {
  62241. var type = decoder.GetEncodedGeometryType(buffer);
  62242. switch (type) {
  62243. case module.TRIANGULAR_MESH:
  62244. geometry = new module.Mesh();
  62245. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62246. break;
  62247. case module.POINT_CLOUD:
  62248. geometry = new module.PointCloud();
  62249. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62250. break;
  62251. default:
  62252. throw new Error("Invalid geometry type " + type);
  62253. }
  62254. if (!status.ok() || !geometry.ptr) {
  62255. throw new Error(status.error_msg());
  62256. }
  62257. var numPoints = geometry.num_points();
  62258. if (type === module.TRIANGULAR_MESH) {
  62259. var numFaces = geometry.num_faces();
  62260. var faceIndices = new module.DracoInt32Array();
  62261. try {
  62262. var indices = new Uint32Array(numFaces * 3);
  62263. for (var i = 0; i < numFaces; i++) {
  62264. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62265. var offset = i * 3;
  62266. indices[offset + 0] = faceIndices.GetValue(0);
  62267. indices[offset + 1] = faceIndices.GetValue(1);
  62268. indices[offset + 2] = faceIndices.GetValue(2);
  62269. }
  62270. vertexData.indices = indices;
  62271. }
  62272. finally {
  62273. module.destroy(faceIndices);
  62274. }
  62275. }
  62276. for (var kind in attributes) {
  62277. var uniqueId = attributes[kind];
  62278. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62279. var dracoData = new module.DracoFloat32Array();
  62280. try {
  62281. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62282. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62283. for (var i = 0; i < babylonData.length; i++) {
  62284. babylonData[i] = dracoData.GetValue(i);
  62285. }
  62286. vertexData.set(babylonData, kind);
  62287. }
  62288. finally {
  62289. module.destroy(dracoData);
  62290. }
  62291. }
  62292. }
  62293. finally {
  62294. if (geometry) {
  62295. module.destroy(geometry);
  62296. }
  62297. module.destroy(decoder);
  62298. module.destroy(buffer);
  62299. }
  62300. return vertexData;
  62301. });
  62302. };
  62303. DracoCompression._GetDecoderModule = function () {
  62304. if (!DracoCompression._DecoderModulePromise) {
  62305. var promise = null;
  62306. var config_1 = {};
  62307. if (typeof DracoDecoderModule !== "undefined") {
  62308. promise = Promise.resolve();
  62309. }
  62310. else {
  62311. var decoder = DracoCompression.Configuration.decoder;
  62312. if (decoder) {
  62313. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62314. promise = Promise.all([
  62315. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62316. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62317. config_1.wasmBinary = data;
  62318. })
  62319. ]);
  62320. }
  62321. else if (decoder.fallbackUrl) {
  62322. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62323. }
  62324. }
  62325. }
  62326. if (!promise) {
  62327. throw new Error("Draco decoder module is not available");
  62328. }
  62329. DracoCompression._DecoderModulePromise = promise.then(function () {
  62330. return new Promise(function (resolve) {
  62331. config_1.onModuleLoaded = function (decoderModule) {
  62332. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62333. resolve({ module: decoderModule });
  62334. };
  62335. DracoDecoderModule(config_1);
  62336. });
  62337. });
  62338. }
  62339. return DracoCompression._DecoderModulePromise;
  62340. };
  62341. DracoCompression._LoadScriptAsync = function (url) {
  62342. return new Promise(function (resolve, reject) {
  62343. BABYLON.Tools.LoadScript(url, function () {
  62344. resolve();
  62345. }, function (message) {
  62346. reject(new Error(message));
  62347. });
  62348. });
  62349. };
  62350. DracoCompression._LoadFileAsync = function (url) {
  62351. return new Promise(function (resolve, reject) {
  62352. BABYLON.Tools.LoadFile(url, function (data) {
  62353. resolve(data);
  62354. }, undefined, undefined, true, function (request, exception) {
  62355. reject(exception);
  62356. });
  62357. });
  62358. };
  62359. /**
  62360. * The configuration. Defaults to the following urls:
  62361. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62362. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62363. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62364. */
  62365. DracoCompression.Configuration = {
  62366. decoder: {
  62367. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62368. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62369. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62370. }
  62371. };
  62372. return DracoCompression;
  62373. }());
  62374. BABYLON.DracoCompression = DracoCompression;
  62375. })(BABYLON || (BABYLON = {}));
  62376. //# sourceMappingURL=babylon.dracoCompression.js.map
  62377. var BABYLON;
  62378. (function (BABYLON) {
  62379. var AudioEngine = /** @class */ (function () {
  62380. function AudioEngine() {
  62381. this._audioContext = null;
  62382. this._audioContextInitialized = false;
  62383. this.canUseWebAudio = false;
  62384. this.WarnedWebAudioUnsupported = false;
  62385. this.unlocked = false;
  62386. this.isMP3supported = false;
  62387. this.isOGGsupported = false;
  62388. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62389. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62390. this.canUseWebAudio = true;
  62391. }
  62392. var audioElem = document.createElement('audio');
  62393. try {
  62394. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62395. this.isMP3supported = true;
  62396. }
  62397. }
  62398. catch (e) {
  62399. // protect error during capability check.
  62400. }
  62401. try {
  62402. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62403. this.isOGGsupported = true;
  62404. }
  62405. }
  62406. catch (e) {
  62407. // protect error during capability check.
  62408. }
  62409. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62410. this._unlockiOSaudio();
  62411. }
  62412. else {
  62413. this.unlocked = true;
  62414. }
  62415. }
  62416. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62417. get: function () {
  62418. if (!this._audioContextInitialized) {
  62419. this._initializeAudioContext();
  62420. }
  62421. return this._audioContext;
  62422. },
  62423. enumerable: true,
  62424. configurable: true
  62425. });
  62426. AudioEngine.prototype._unlockiOSaudio = function () {
  62427. var _this = this;
  62428. var unlockaudio = function () {
  62429. if (!_this.audioContext) {
  62430. return;
  62431. }
  62432. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62433. var source = _this.audioContext.createBufferSource();
  62434. source.buffer = buffer;
  62435. source.connect(_this.audioContext.destination);
  62436. source.start(0);
  62437. setTimeout(function () {
  62438. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62439. _this.unlocked = true;
  62440. window.removeEventListener('touchend', unlockaudio, false);
  62441. if (_this.onAudioUnlocked) {
  62442. _this.onAudioUnlocked();
  62443. }
  62444. }
  62445. }, 0);
  62446. };
  62447. window.addEventListener('touchend', unlockaudio, false);
  62448. };
  62449. AudioEngine.prototype._initializeAudioContext = function () {
  62450. try {
  62451. if (this.canUseWebAudio) {
  62452. this._audioContext = new AudioContext();
  62453. // create a global volume gain node
  62454. this.masterGain = this._audioContext.createGain();
  62455. this.masterGain.gain.value = 1;
  62456. this.masterGain.connect(this._audioContext.destination);
  62457. this._audioContextInitialized = true;
  62458. }
  62459. }
  62460. catch (e) {
  62461. this.canUseWebAudio = false;
  62462. BABYLON.Tools.Error("Web Audio: " + e.message);
  62463. }
  62464. };
  62465. AudioEngine.prototype.dispose = function () {
  62466. if (this.canUseWebAudio && this._audioContextInitialized) {
  62467. if (this._connectedAnalyser && this._audioContext) {
  62468. this._connectedAnalyser.stopDebugCanvas();
  62469. this._connectedAnalyser.dispose();
  62470. this.masterGain.disconnect();
  62471. this.masterGain.connect(this._audioContext.destination);
  62472. this._connectedAnalyser = null;
  62473. }
  62474. this.masterGain.gain.value = 1;
  62475. }
  62476. this.WarnedWebAudioUnsupported = false;
  62477. };
  62478. AudioEngine.prototype.getGlobalVolume = function () {
  62479. if (this.canUseWebAudio && this._audioContextInitialized) {
  62480. return this.masterGain.gain.value;
  62481. }
  62482. else {
  62483. return -1;
  62484. }
  62485. };
  62486. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62487. if (this.canUseWebAudio && this._audioContextInitialized) {
  62488. this.masterGain.gain.value = newVolume;
  62489. }
  62490. };
  62491. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62492. if (this._connectedAnalyser) {
  62493. this._connectedAnalyser.stopDebugCanvas();
  62494. }
  62495. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62496. this._connectedAnalyser = analyser;
  62497. this.masterGain.disconnect();
  62498. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62499. }
  62500. };
  62501. return AudioEngine;
  62502. }());
  62503. BABYLON.AudioEngine = AudioEngine;
  62504. })(BABYLON || (BABYLON = {}));
  62505. //# sourceMappingURL=babylon.audioEngine.js.map
  62506. var BABYLON;
  62507. (function (BABYLON) {
  62508. var Sound = /** @class */ (function () {
  62509. /**
  62510. * Create a sound and attach it to a scene
  62511. * @param name Name of your sound
  62512. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62513. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62514. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62515. */
  62516. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62517. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62518. var _this = this;
  62519. this.autoplay = false;
  62520. this.loop = false;
  62521. this.useCustomAttenuation = false;
  62522. this.spatialSound = false;
  62523. this.refDistance = 1;
  62524. this.rolloffFactor = 1;
  62525. this.maxDistance = 100;
  62526. this.distanceModel = "linear";
  62527. this._panningModel = "equalpower";
  62528. this._playbackRate = 1;
  62529. this._streaming = false;
  62530. this._startTime = 0;
  62531. this._startOffset = 0;
  62532. this._position = BABYLON.Vector3.Zero();
  62533. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62534. this._volume = 1;
  62535. this._isReadyToPlay = false;
  62536. this.isPlaying = false;
  62537. this.isPaused = false;
  62538. this._isDirectional = false;
  62539. // Used if you'd like to create a directional sound.
  62540. // If not set, the sound will be omnidirectional
  62541. this._coneInnerAngle = 360;
  62542. this._coneOuterAngle = 360;
  62543. this._coneOuterGain = 0;
  62544. this._isOutputConnected = false;
  62545. this._urlType = "Unknown";
  62546. this.name = name;
  62547. this._scene = scene;
  62548. this._readyToPlayCallback = readyToPlayCallback;
  62549. // Default custom attenuation function is a linear attenuation
  62550. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62551. if (currentDistance < maxDistance) {
  62552. return currentVolume * (1 - currentDistance / maxDistance);
  62553. }
  62554. else {
  62555. return 0;
  62556. }
  62557. };
  62558. if (options) {
  62559. this.autoplay = options.autoplay || false;
  62560. this.loop = options.loop || false;
  62561. // if volume === 0, we need another way to check this option
  62562. if (options.volume !== undefined) {
  62563. this._volume = options.volume;
  62564. }
  62565. this.spatialSound = options.spatialSound || false;
  62566. this.maxDistance = options.maxDistance || 100;
  62567. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62568. this.rolloffFactor = options.rolloffFactor || 1;
  62569. this.refDistance = options.refDistance || 1;
  62570. this.distanceModel = options.distanceModel || "linear";
  62571. this._playbackRate = options.playbackRate || 1;
  62572. this._streaming = options.streaming || false;
  62573. }
  62574. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62575. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62576. this._soundGain.gain.value = this._volume;
  62577. this._inputAudioNode = this._soundGain;
  62578. this._ouputAudioNode = this._soundGain;
  62579. if (this.spatialSound) {
  62580. this._createSpatialParameters();
  62581. }
  62582. this._scene.mainSoundTrack.AddSound(this);
  62583. var validParameter = true;
  62584. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62585. if (urlOrArrayBuffer) {
  62586. try {
  62587. if (typeof (urlOrArrayBuffer) === "string")
  62588. this._urlType = "String";
  62589. if (Array.isArray(urlOrArrayBuffer))
  62590. this._urlType = "Array";
  62591. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62592. this._urlType = "ArrayBuffer";
  62593. var urls = [];
  62594. var codecSupportedFound = false;
  62595. switch (this._urlType) {
  62596. case "ArrayBuffer":
  62597. if (urlOrArrayBuffer.byteLength > 0) {
  62598. codecSupportedFound = true;
  62599. this._soundLoaded(urlOrArrayBuffer);
  62600. }
  62601. break;
  62602. case "String":
  62603. urls.push(urlOrArrayBuffer);
  62604. case "Array":
  62605. if (urls.length === 0)
  62606. urls = urlOrArrayBuffer;
  62607. // If we found a supported format, we load it immediately and stop the loop
  62608. for (var i = 0; i < urls.length; i++) {
  62609. var url = urls[i];
  62610. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62611. codecSupportedFound = true;
  62612. }
  62613. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62614. codecSupportedFound = true;
  62615. }
  62616. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62617. codecSupportedFound = true;
  62618. }
  62619. if (url.indexOf("blob:") !== -1) {
  62620. codecSupportedFound = true;
  62621. }
  62622. if (codecSupportedFound) {
  62623. // Loading sound using XHR2
  62624. if (!this._streaming) {
  62625. this._scene._loadFile(url, function (data) {
  62626. _this._soundLoaded(data);
  62627. }, undefined, true, true, function (exception) {
  62628. if (exception) {
  62629. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62630. }
  62631. BABYLON.Tools.Error("Sound creation aborted.");
  62632. _this._scene.mainSoundTrack.RemoveSound(_this);
  62633. });
  62634. }
  62635. // Streaming sound using HTML5 Audio tag
  62636. else {
  62637. this._htmlAudioElement = new Audio(url);
  62638. this._htmlAudioElement.controls = false;
  62639. this._htmlAudioElement.loop = this.loop;
  62640. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62641. this._htmlAudioElement.preload = "auto";
  62642. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62643. _this._isReadyToPlay = true;
  62644. if (_this.autoplay) {
  62645. _this.play();
  62646. }
  62647. if (_this._readyToPlayCallback) {
  62648. _this._readyToPlayCallback();
  62649. }
  62650. });
  62651. document.body.appendChild(this._htmlAudioElement);
  62652. }
  62653. break;
  62654. }
  62655. }
  62656. break;
  62657. default:
  62658. validParameter = false;
  62659. break;
  62660. }
  62661. if (!validParameter) {
  62662. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62663. }
  62664. else {
  62665. if (!codecSupportedFound) {
  62666. this._isReadyToPlay = true;
  62667. // Simulating a ready to play event to avoid breaking code path
  62668. if (this._readyToPlayCallback) {
  62669. window.setTimeout(function () {
  62670. if (_this._readyToPlayCallback) {
  62671. _this._readyToPlayCallback();
  62672. }
  62673. }, 1000);
  62674. }
  62675. }
  62676. }
  62677. }
  62678. catch (ex) {
  62679. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62680. this._scene.mainSoundTrack.RemoveSound(this);
  62681. }
  62682. }
  62683. }
  62684. else {
  62685. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62686. this._scene.mainSoundTrack.AddSound(this);
  62687. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62688. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62689. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62690. }
  62691. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62692. if (this._readyToPlayCallback) {
  62693. window.setTimeout(function () {
  62694. if (_this._readyToPlayCallback) {
  62695. _this._readyToPlayCallback();
  62696. }
  62697. }, 1000);
  62698. }
  62699. }
  62700. }
  62701. Sound.prototype.dispose = function () {
  62702. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62703. if (this.isPlaying) {
  62704. this.stop();
  62705. }
  62706. this._isReadyToPlay = false;
  62707. if (this.soundTrackId === -1) {
  62708. this._scene.mainSoundTrack.RemoveSound(this);
  62709. }
  62710. else {
  62711. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62712. }
  62713. if (this._soundGain) {
  62714. this._soundGain.disconnect();
  62715. this._soundGain = null;
  62716. }
  62717. if (this._soundPanner) {
  62718. this._soundPanner.disconnect();
  62719. this._soundPanner = null;
  62720. }
  62721. if (this._soundSource) {
  62722. this._soundSource.disconnect();
  62723. this._soundSource = null;
  62724. }
  62725. this._audioBuffer = null;
  62726. if (this._htmlAudioElement) {
  62727. this._htmlAudioElement.pause();
  62728. this._htmlAudioElement.src = "";
  62729. document.body.removeChild(this._htmlAudioElement);
  62730. }
  62731. if (this._connectedMesh && this._registerFunc) {
  62732. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62733. this._connectedMesh = null;
  62734. }
  62735. }
  62736. };
  62737. Sound.prototype.isReady = function () {
  62738. return this._isReadyToPlay;
  62739. };
  62740. Sound.prototype._soundLoaded = function (audioData) {
  62741. var _this = this;
  62742. if (!BABYLON.Engine.audioEngine.audioContext) {
  62743. return;
  62744. }
  62745. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62746. _this._audioBuffer = buffer;
  62747. _this._isReadyToPlay = true;
  62748. if (_this.autoplay) {
  62749. _this.play();
  62750. }
  62751. if (_this._readyToPlayCallback) {
  62752. _this._readyToPlayCallback();
  62753. }
  62754. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62755. };
  62756. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62757. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62758. this._audioBuffer = audioBuffer;
  62759. this._isReadyToPlay = true;
  62760. }
  62761. };
  62762. Sound.prototype.updateOptions = function (options) {
  62763. if (options) {
  62764. this.loop = options.loop || this.loop;
  62765. this.maxDistance = options.maxDistance || this.maxDistance;
  62766. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62767. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62768. this.refDistance = options.refDistance || this.refDistance;
  62769. this.distanceModel = options.distanceModel || this.distanceModel;
  62770. this._playbackRate = options.playbackRate || this._playbackRate;
  62771. this._updateSpatialParameters();
  62772. if (this.isPlaying) {
  62773. if (this._streaming) {
  62774. this._htmlAudioElement.playbackRate = this._playbackRate;
  62775. }
  62776. else {
  62777. if (this._soundSource) {
  62778. this._soundSource.playbackRate.value = this._playbackRate;
  62779. }
  62780. }
  62781. }
  62782. }
  62783. };
  62784. Sound.prototype._createSpatialParameters = function () {
  62785. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62786. if (this._scene.headphone) {
  62787. this._panningModel = "HRTF";
  62788. }
  62789. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62790. this._updateSpatialParameters();
  62791. this._soundPanner.connect(this._ouputAudioNode);
  62792. this._inputAudioNode = this._soundPanner;
  62793. }
  62794. };
  62795. Sound.prototype._updateSpatialParameters = function () {
  62796. if (this.spatialSound && this._soundPanner) {
  62797. if (this.useCustomAttenuation) {
  62798. // Tricks to disable in a way embedded Web Audio attenuation
  62799. this._soundPanner.distanceModel = "linear";
  62800. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62801. this._soundPanner.refDistance = 1;
  62802. this._soundPanner.rolloffFactor = 1;
  62803. this._soundPanner.panningModel = this._panningModel;
  62804. }
  62805. else {
  62806. this._soundPanner.distanceModel = this.distanceModel;
  62807. this._soundPanner.maxDistance = this.maxDistance;
  62808. this._soundPanner.refDistance = this.refDistance;
  62809. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62810. this._soundPanner.panningModel = this._panningModel;
  62811. }
  62812. }
  62813. };
  62814. Sound.prototype.switchPanningModelToHRTF = function () {
  62815. this._panningModel = "HRTF";
  62816. this._switchPanningModel();
  62817. };
  62818. Sound.prototype.switchPanningModelToEqualPower = function () {
  62819. this._panningModel = "equalpower";
  62820. this._switchPanningModel();
  62821. };
  62822. Sound.prototype._switchPanningModel = function () {
  62823. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62824. this._soundPanner.panningModel = this._panningModel;
  62825. }
  62826. };
  62827. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62828. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62829. if (this._isOutputConnected) {
  62830. this._ouputAudioNode.disconnect();
  62831. }
  62832. this._ouputAudioNode.connect(soundTrackAudioNode);
  62833. this._isOutputConnected = true;
  62834. }
  62835. };
  62836. /**
  62837. * Transform this sound into a directional source
  62838. * @param coneInnerAngle Size of the inner cone in degree
  62839. * @param coneOuterAngle Size of the outer cone in degree
  62840. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62841. */
  62842. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62843. if (coneOuterAngle < coneInnerAngle) {
  62844. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62845. return;
  62846. }
  62847. this._coneInnerAngle = coneInnerAngle;
  62848. this._coneOuterAngle = coneOuterAngle;
  62849. this._coneOuterGain = coneOuterGain;
  62850. this._isDirectional = true;
  62851. if (this.isPlaying && this.loop) {
  62852. this.stop();
  62853. this.play();
  62854. }
  62855. };
  62856. Sound.prototype.setPosition = function (newPosition) {
  62857. this._position = newPosition;
  62858. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62859. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62860. }
  62861. };
  62862. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62863. this._localDirection = newLocalDirection;
  62864. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62865. this._updateDirection();
  62866. }
  62867. };
  62868. Sound.prototype._updateDirection = function () {
  62869. if (!this._connectedMesh || !this._soundPanner) {
  62870. return;
  62871. }
  62872. var mat = this._connectedMesh.getWorldMatrix();
  62873. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62874. direction.normalize();
  62875. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62876. };
  62877. Sound.prototype.updateDistanceFromListener = function () {
  62878. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62879. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62880. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62881. }
  62882. };
  62883. Sound.prototype.setAttenuationFunction = function (callback) {
  62884. this._customAttenuationFunction = callback;
  62885. };
  62886. /**
  62887. * Play the sound
  62888. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62889. * @param offset (optional) Start the sound setting it at a specific time
  62890. */
  62891. Sound.prototype.play = function (time, offset) {
  62892. var _this = this;
  62893. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62894. try {
  62895. if (this._startOffset < 0) {
  62896. time = -this._startOffset;
  62897. this._startOffset = 0;
  62898. }
  62899. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62900. if (!this._soundSource || !this._streamingSource) {
  62901. if (this.spatialSound && this._soundPanner) {
  62902. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62903. if (this._isDirectional) {
  62904. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62905. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62906. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62907. if (this._connectedMesh) {
  62908. this._updateDirection();
  62909. }
  62910. else {
  62911. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62912. }
  62913. }
  62914. }
  62915. }
  62916. if (this._streaming) {
  62917. if (!this._streamingSource) {
  62918. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62919. this._htmlAudioElement.onended = function () { _this._onended(); };
  62920. this._htmlAudioElement.playbackRate = this._playbackRate;
  62921. }
  62922. this._streamingSource.disconnect();
  62923. this._streamingSource.connect(this._inputAudioNode);
  62924. this._htmlAudioElement.play();
  62925. }
  62926. else {
  62927. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62928. this._soundSource.buffer = this._audioBuffer;
  62929. this._soundSource.connect(this._inputAudioNode);
  62930. this._soundSource.loop = this.loop;
  62931. this._soundSource.playbackRate.value = this._playbackRate;
  62932. this._soundSource.onended = function () { _this._onended(); };
  62933. if (this._soundSource.buffer) {
  62934. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62935. }
  62936. }
  62937. this._startTime = startTime;
  62938. this.isPlaying = true;
  62939. this.isPaused = false;
  62940. }
  62941. catch (ex) {
  62942. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62943. }
  62944. }
  62945. };
  62946. Sound.prototype._onended = function () {
  62947. this.isPlaying = false;
  62948. if (this.onended) {
  62949. this.onended();
  62950. }
  62951. };
  62952. /**
  62953. * Stop the sound
  62954. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62955. */
  62956. Sound.prototype.stop = function (time) {
  62957. if (this.isPlaying) {
  62958. if (this._streaming) {
  62959. this._htmlAudioElement.pause();
  62960. // Test needed for Firefox or it will generate an Invalid State Error
  62961. if (this._htmlAudioElement.currentTime > 0) {
  62962. this._htmlAudioElement.currentTime = 0;
  62963. }
  62964. }
  62965. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62966. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62967. this._soundSource.stop(stopTime);
  62968. this._soundSource.onended = function () { };
  62969. if (!this.isPaused) {
  62970. this._startOffset = 0;
  62971. }
  62972. }
  62973. this.isPlaying = false;
  62974. }
  62975. };
  62976. Sound.prototype.pause = function () {
  62977. if (this.isPlaying) {
  62978. this.isPaused = true;
  62979. if (this._streaming) {
  62980. this._htmlAudioElement.pause();
  62981. }
  62982. else if (BABYLON.Engine.audioEngine.audioContext) {
  62983. this.stop(0);
  62984. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62985. }
  62986. }
  62987. };
  62988. Sound.prototype.setVolume = function (newVolume, time) {
  62989. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62990. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62991. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62992. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62993. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62994. }
  62995. else {
  62996. this._soundGain.gain.value = newVolume;
  62997. }
  62998. }
  62999. this._volume = newVolume;
  63000. };
  63001. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63002. this._playbackRate = newPlaybackRate;
  63003. if (this.isPlaying) {
  63004. if (this._streaming) {
  63005. this._htmlAudioElement.playbackRate = this._playbackRate;
  63006. }
  63007. else if (this._soundSource) {
  63008. this._soundSource.playbackRate.value = this._playbackRate;
  63009. }
  63010. }
  63011. };
  63012. Sound.prototype.getVolume = function () {
  63013. return this._volume;
  63014. };
  63015. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63016. var _this = this;
  63017. if (this._connectedMesh && this._registerFunc) {
  63018. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63019. this._registerFunc = null;
  63020. }
  63021. this._connectedMesh = meshToConnectTo;
  63022. if (!this.spatialSound) {
  63023. this.spatialSound = true;
  63024. this._createSpatialParameters();
  63025. if (this.isPlaying && this.loop) {
  63026. this.stop();
  63027. this.play();
  63028. }
  63029. }
  63030. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63031. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63032. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63033. };
  63034. Sound.prototype.detachFromMesh = function () {
  63035. if (this._connectedMesh && this._registerFunc) {
  63036. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63037. this._registerFunc = null;
  63038. this._connectedMesh = null;
  63039. }
  63040. };
  63041. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63042. if (!node.getBoundingInfo) {
  63043. return;
  63044. }
  63045. var mesh = node;
  63046. var boundingInfo = mesh.getBoundingInfo();
  63047. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63048. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63049. this._updateDirection();
  63050. }
  63051. };
  63052. Sound.prototype.clone = function () {
  63053. var _this = this;
  63054. if (!this._streaming) {
  63055. var setBufferAndRun = function () {
  63056. if (_this._isReadyToPlay) {
  63057. clonedSound._audioBuffer = _this.getAudioBuffer();
  63058. clonedSound._isReadyToPlay = true;
  63059. if (clonedSound.autoplay) {
  63060. clonedSound.play();
  63061. }
  63062. }
  63063. else {
  63064. window.setTimeout(setBufferAndRun, 300);
  63065. }
  63066. };
  63067. var currentOptions = {
  63068. autoplay: this.autoplay, loop: this.loop,
  63069. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63070. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63071. refDistance: this.refDistance, distanceModel: this.distanceModel
  63072. };
  63073. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63074. if (this.useCustomAttenuation) {
  63075. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63076. }
  63077. clonedSound.setPosition(this._position);
  63078. clonedSound.setPlaybackRate(this._playbackRate);
  63079. setBufferAndRun();
  63080. return clonedSound;
  63081. }
  63082. // Can't clone a streaming sound
  63083. else {
  63084. return null;
  63085. }
  63086. };
  63087. Sound.prototype.getAudioBuffer = function () {
  63088. return this._audioBuffer;
  63089. };
  63090. Sound.prototype.serialize = function () {
  63091. var serializationObject = {
  63092. name: this.name,
  63093. url: this.name,
  63094. autoplay: this.autoplay,
  63095. loop: this.loop,
  63096. volume: this._volume,
  63097. spatialSound: this.spatialSound,
  63098. maxDistance: this.maxDistance,
  63099. rolloffFactor: this.rolloffFactor,
  63100. refDistance: this.refDistance,
  63101. distanceModel: this.distanceModel,
  63102. playbackRate: this._playbackRate,
  63103. panningModel: this._panningModel,
  63104. soundTrackId: this.soundTrackId
  63105. };
  63106. if (this.spatialSound) {
  63107. if (this._connectedMesh)
  63108. serializationObject.connectedMeshId = this._connectedMesh.id;
  63109. serializationObject.position = this._position.asArray();
  63110. serializationObject.refDistance = this.refDistance;
  63111. serializationObject.distanceModel = this.distanceModel;
  63112. serializationObject.isDirectional = this._isDirectional;
  63113. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63114. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63115. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63116. serializationObject.coneOuterGain = this._coneOuterGain;
  63117. }
  63118. return serializationObject;
  63119. };
  63120. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63121. var soundName = parsedSound.name;
  63122. var soundUrl;
  63123. if (parsedSound.url) {
  63124. soundUrl = rootUrl + parsedSound.url;
  63125. }
  63126. else {
  63127. soundUrl = rootUrl + soundName;
  63128. }
  63129. var options = {
  63130. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63131. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63132. rolloffFactor: parsedSound.rolloffFactor,
  63133. refDistance: parsedSound.refDistance,
  63134. distanceModel: parsedSound.distanceModel,
  63135. playbackRate: parsedSound.playbackRate
  63136. };
  63137. var newSound;
  63138. if (!sourceSound) {
  63139. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63140. scene._addPendingData(newSound);
  63141. }
  63142. else {
  63143. var setBufferAndRun = function () {
  63144. if (sourceSound._isReadyToPlay) {
  63145. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63146. newSound._isReadyToPlay = true;
  63147. if (newSound.autoplay) {
  63148. newSound.play();
  63149. }
  63150. }
  63151. else {
  63152. window.setTimeout(setBufferAndRun, 300);
  63153. }
  63154. };
  63155. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63156. setBufferAndRun();
  63157. }
  63158. if (parsedSound.position) {
  63159. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63160. newSound.setPosition(soundPosition);
  63161. }
  63162. if (parsedSound.isDirectional) {
  63163. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63164. if (parsedSound.localDirectionToMesh) {
  63165. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63166. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63167. }
  63168. }
  63169. if (parsedSound.connectedMeshId) {
  63170. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63171. if (connectedMesh) {
  63172. newSound.attachToMesh(connectedMesh);
  63173. }
  63174. }
  63175. return newSound;
  63176. };
  63177. return Sound;
  63178. }());
  63179. BABYLON.Sound = Sound;
  63180. })(BABYLON || (BABYLON = {}));
  63181. //# sourceMappingURL=babylon.sound.js.map
  63182. var BABYLON;
  63183. (function (BABYLON) {
  63184. var SoundTrack = /** @class */ (function () {
  63185. function SoundTrack(scene, options) {
  63186. this.id = -1;
  63187. this._isMainTrack = false;
  63188. this._isInitialized = false;
  63189. this._scene = scene;
  63190. this.soundCollection = new Array();
  63191. this._options = options;
  63192. if (!this._isMainTrack) {
  63193. this._scene.soundTracks.push(this);
  63194. this.id = this._scene.soundTracks.length - 1;
  63195. }
  63196. }
  63197. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63198. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63199. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63200. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63201. if (this._options) {
  63202. if (this._options.volume) {
  63203. this._outputAudioNode.gain.value = this._options.volume;
  63204. }
  63205. if (this._options.mainTrack) {
  63206. this._isMainTrack = this._options.mainTrack;
  63207. }
  63208. }
  63209. this._isInitialized = true;
  63210. }
  63211. };
  63212. SoundTrack.prototype.dispose = function () {
  63213. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63214. if (this._connectedAnalyser) {
  63215. this._connectedAnalyser.stopDebugCanvas();
  63216. }
  63217. while (this.soundCollection.length) {
  63218. this.soundCollection[0].dispose();
  63219. }
  63220. if (this._outputAudioNode) {
  63221. this._outputAudioNode.disconnect();
  63222. }
  63223. this._outputAudioNode = null;
  63224. }
  63225. };
  63226. SoundTrack.prototype.AddSound = function (sound) {
  63227. if (!this._isInitialized) {
  63228. this._initializeSoundTrackAudioGraph();
  63229. }
  63230. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63231. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63232. }
  63233. if (sound.soundTrackId) {
  63234. if (sound.soundTrackId === -1) {
  63235. this._scene.mainSoundTrack.RemoveSound(sound);
  63236. }
  63237. else {
  63238. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63239. }
  63240. }
  63241. this.soundCollection.push(sound);
  63242. sound.soundTrackId = this.id;
  63243. };
  63244. SoundTrack.prototype.RemoveSound = function (sound) {
  63245. var index = this.soundCollection.indexOf(sound);
  63246. if (index !== -1) {
  63247. this.soundCollection.splice(index, 1);
  63248. }
  63249. };
  63250. SoundTrack.prototype.setVolume = function (newVolume) {
  63251. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63252. this._outputAudioNode.gain.value = newVolume;
  63253. }
  63254. };
  63255. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63256. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63257. for (var i = 0; i < this.soundCollection.length; i++) {
  63258. this.soundCollection[i].switchPanningModelToHRTF();
  63259. }
  63260. }
  63261. };
  63262. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63263. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63264. for (var i = 0; i < this.soundCollection.length; i++) {
  63265. this.soundCollection[i].switchPanningModelToEqualPower();
  63266. }
  63267. }
  63268. };
  63269. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63270. if (this._connectedAnalyser) {
  63271. this._connectedAnalyser.stopDebugCanvas();
  63272. }
  63273. this._connectedAnalyser = analyser;
  63274. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63275. this._outputAudioNode.disconnect();
  63276. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63277. }
  63278. };
  63279. return SoundTrack;
  63280. }());
  63281. BABYLON.SoundTrack = SoundTrack;
  63282. })(BABYLON || (BABYLON = {}));
  63283. //# sourceMappingURL=babylon.soundtrack.js.map
  63284. var BABYLON;
  63285. (function (BABYLON) {
  63286. /**
  63287. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63288. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63289. */
  63290. var Analyser = /** @class */ (function () {
  63291. /**
  63292. * Creates a new analyser
  63293. * @param scene defines hosting scene
  63294. */
  63295. function Analyser(scene) {
  63296. /**
  63297. * Gets or sets the smoothing
  63298. * @ignorenaming
  63299. */
  63300. this.SMOOTHING = 0.75;
  63301. /**
  63302. * Gets or sets the FFT table size
  63303. * @ignorenaming
  63304. */
  63305. this.FFT_SIZE = 512;
  63306. /**
  63307. * Gets or sets the bar graph amplitude
  63308. * @ignorenaming
  63309. */
  63310. this.BARGRAPHAMPLITUDE = 256;
  63311. /**
  63312. * Gets or sets the position of the debug canvas
  63313. * @ignorenaming
  63314. */
  63315. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63316. /**
  63317. * Gets or sets the debug canvas size
  63318. * @ignorenaming
  63319. */
  63320. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63321. this._scene = scene;
  63322. this._audioEngine = BABYLON.Engine.audioEngine;
  63323. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63324. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63325. this._webAudioAnalyser.minDecibels = -140;
  63326. this._webAudioAnalyser.maxDecibels = 0;
  63327. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63328. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63329. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63330. }
  63331. }
  63332. /**
  63333. * Get the number of data values you will have to play with for the visualization
  63334. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63335. * @returns a number
  63336. */
  63337. Analyser.prototype.getFrequencyBinCount = function () {
  63338. if (this._audioEngine.canUseWebAudio) {
  63339. return this._webAudioAnalyser.frequencyBinCount;
  63340. }
  63341. else {
  63342. return 0;
  63343. }
  63344. };
  63345. /**
  63346. * Gets the current frequency data as a byte array
  63347. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63348. * @returns a Uint8Array
  63349. */
  63350. Analyser.prototype.getByteFrequencyData = function () {
  63351. if (this._audioEngine.canUseWebAudio) {
  63352. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63353. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63354. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63355. }
  63356. return this._byteFreqs;
  63357. };
  63358. /**
  63359. * Gets the current waveform as a byte array
  63360. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63361. * @returns a Uint8Array
  63362. */
  63363. Analyser.prototype.getByteTimeDomainData = function () {
  63364. if (this._audioEngine.canUseWebAudio) {
  63365. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63366. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63367. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63368. }
  63369. return this._byteTime;
  63370. };
  63371. /**
  63372. * Gets the current frequency data as a float array
  63373. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63374. * @returns a Float32Array
  63375. */
  63376. Analyser.prototype.getFloatFrequencyData = function () {
  63377. if (this._audioEngine.canUseWebAudio) {
  63378. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63379. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63380. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63381. }
  63382. return this._floatFreqs;
  63383. };
  63384. /**
  63385. * Renders the debug canvas
  63386. */
  63387. Analyser.prototype.drawDebugCanvas = function () {
  63388. var _this = this;
  63389. if (this._audioEngine.canUseWebAudio) {
  63390. if (!this._debugCanvas) {
  63391. this._debugCanvas = document.createElement("canvas");
  63392. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63393. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63394. this._debugCanvas.style.position = "absolute";
  63395. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63396. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63397. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63398. document.body.appendChild(this._debugCanvas);
  63399. this._registerFunc = function () {
  63400. _this.drawDebugCanvas();
  63401. };
  63402. this._scene.registerBeforeRender(this._registerFunc);
  63403. }
  63404. if (this._registerFunc && this._debugCanvasContext) {
  63405. var workingArray = this.getByteFrequencyData();
  63406. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63407. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63408. // Draw the frequency domain chart.
  63409. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63410. var value = workingArray[i];
  63411. var percent = value / this.BARGRAPHAMPLITUDE;
  63412. var height = this.DEBUGCANVASSIZE.height * percent;
  63413. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63414. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63415. var hue = i / this.getFrequencyBinCount() * 360;
  63416. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63417. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63418. }
  63419. }
  63420. }
  63421. };
  63422. /**
  63423. * Stops rendering the debug canvas and removes it
  63424. */
  63425. Analyser.prototype.stopDebugCanvas = function () {
  63426. if (this._debugCanvas) {
  63427. if (this._registerFunc) {
  63428. this._scene.unregisterBeforeRender(this._registerFunc);
  63429. this._registerFunc = null;
  63430. }
  63431. document.body.removeChild(this._debugCanvas);
  63432. this._debugCanvas = null;
  63433. this._debugCanvasContext = null;
  63434. }
  63435. };
  63436. /**
  63437. * Connects two audio nodes
  63438. * @param inputAudioNode defines first node to connect
  63439. * @param outputAudioNode defines second node to connect
  63440. */
  63441. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63442. if (this._audioEngine.canUseWebAudio) {
  63443. inputAudioNode.connect(this._webAudioAnalyser);
  63444. this._webAudioAnalyser.connect(outputAudioNode);
  63445. }
  63446. };
  63447. /**
  63448. * Releases all associated resources
  63449. */
  63450. Analyser.prototype.dispose = function () {
  63451. if (this._audioEngine.canUseWebAudio) {
  63452. this._webAudioAnalyser.disconnect();
  63453. }
  63454. };
  63455. return Analyser;
  63456. }());
  63457. BABYLON.Analyser = Analyser;
  63458. })(BABYLON || (BABYLON = {}));
  63459. //# sourceMappingURL=babylon.analyser.js.map
  63460. var BABYLON;
  63461. (function (BABYLON) {
  63462. var CubeTexture = /** @class */ (function (_super) {
  63463. __extends(CubeTexture, _super);
  63464. /**
  63465. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63466. * as prefiltered data.
  63467. * @param rootUrl defines the url of the texture or the root name of the six images
  63468. * @param scene defines the scene the texture is attached to
  63469. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63470. * @param noMipmap defines if mipmaps should be created or not
  63471. * @param files defines the six files to load for the different faces
  63472. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63473. * @param onError defines a callback triggered in case of error during load
  63474. * @param format defines the internal format to use for the texture once loaded
  63475. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63476. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63477. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63478. * @return the cube texture
  63479. */
  63480. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63481. if (extensions === void 0) { extensions = null; }
  63482. if (noMipmap === void 0) { noMipmap = false; }
  63483. if (files === void 0) { files = null; }
  63484. if (onLoad === void 0) { onLoad = null; }
  63485. if (onError === void 0) { onError = null; }
  63486. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63487. if (prefiltered === void 0) { prefiltered = false; }
  63488. if (forcedExtension === void 0) { forcedExtension = null; }
  63489. if (createPolynomials === void 0) { createPolynomials = false; }
  63490. var _this = _super.call(this, scene) || this;
  63491. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63492. /**
  63493. * Gets or sets the center of the bounding box associated with the cube texture
  63494. * It must define where the camera used to render the texture was set
  63495. */
  63496. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63497. _this._rotationY = 0;
  63498. _this.name = rootUrl;
  63499. _this.url = rootUrl;
  63500. _this._noMipmap = noMipmap;
  63501. _this.hasAlpha = false;
  63502. _this._format = format;
  63503. _this._prefiltered = prefiltered;
  63504. _this.isCube = true;
  63505. _this._textureMatrix = BABYLON.Matrix.Identity();
  63506. _this._createPolynomials = createPolynomials;
  63507. if (prefiltered) {
  63508. _this.gammaSpace = false;
  63509. }
  63510. if (!rootUrl && !files) {
  63511. return _this;
  63512. }
  63513. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63514. var lastDot = rootUrl.lastIndexOf(".");
  63515. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63516. var isDDS = (extension === ".dds");
  63517. if (!files) {
  63518. if (!isDDS && !extensions) {
  63519. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63520. }
  63521. files = [];
  63522. if (extensions) {
  63523. for (var index = 0; index < extensions.length; index++) {
  63524. files.push(rootUrl + extensions[index]);
  63525. }
  63526. }
  63527. }
  63528. _this._files = files;
  63529. if (!_this._texture) {
  63530. if (!scene.useDelayedTextureLoading) {
  63531. if (prefiltered) {
  63532. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63533. }
  63534. else {
  63535. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63536. }
  63537. }
  63538. else {
  63539. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63540. }
  63541. }
  63542. else if (onLoad) {
  63543. if (_this._texture.isReady) {
  63544. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63545. }
  63546. else {
  63547. _this._texture.onLoadedObservable.add(onLoad);
  63548. }
  63549. }
  63550. return _this;
  63551. }
  63552. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63553. get: function () {
  63554. return this._boundingBoxSize;
  63555. },
  63556. /**
  63557. * Gets or sets the size of the bounding box associated with the cube texture
  63558. * When defined, the cubemap will switch to local mode
  63559. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63560. * @example https://www.babylonjs-playground.com/#RNASML
  63561. */
  63562. set: function (value) {
  63563. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63564. return;
  63565. }
  63566. this._boundingBoxSize = value;
  63567. var scene = this.getScene();
  63568. if (scene) {
  63569. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63570. }
  63571. },
  63572. enumerable: true,
  63573. configurable: true
  63574. });
  63575. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63576. /**
  63577. * Gets texture matrix rotation angle around Y axis radians.
  63578. */
  63579. get: function () {
  63580. return this._rotationY;
  63581. },
  63582. /**
  63583. * Sets texture matrix rotation angle around Y axis in radians.
  63584. */
  63585. set: function (value) {
  63586. this._rotationY = value;
  63587. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63588. },
  63589. enumerable: true,
  63590. configurable: true
  63591. });
  63592. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63593. var rootUrlKey = "";
  63594. files.forEach(function (url) { return rootUrlKey += url; });
  63595. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63596. };
  63597. /**
  63598. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63599. * @param url defines the url of the prefiltered texture
  63600. * @param scene defines the scene the texture is attached to
  63601. * @param forcedExtension defines the extension of the file if different from the url
  63602. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63603. * @return the prefiltered texture
  63604. */
  63605. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63606. if (forcedExtension === void 0) { forcedExtension = null; }
  63607. if (createPolynomials === void 0) { createPolynomials = true; }
  63608. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63609. };
  63610. // Methods
  63611. CubeTexture.prototype.delayLoad = function () {
  63612. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63613. return;
  63614. }
  63615. var scene = this.getScene();
  63616. if (!scene) {
  63617. return;
  63618. }
  63619. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63620. this._texture = this._getFromCache(this.url, this._noMipmap);
  63621. if (!this._texture) {
  63622. if (this._prefiltered) {
  63623. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63624. }
  63625. else {
  63626. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63627. }
  63628. }
  63629. };
  63630. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63631. return this._textureMatrix;
  63632. };
  63633. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63634. this._textureMatrix = value;
  63635. };
  63636. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63637. var texture = BABYLON.SerializationHelper.Parse(function () {
  63638. var prefiltered = false;
  63639. if (parsedTexture.prefiltered) {
  63640. prefiltered = parsedTexture.prefiltered;
  63641. }
  63642. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63643. }, parsedTexture, scene);
  63644. // Local Cubemaps
  63645. if (parsedTexture.boundingBoxPosition) {
  63646. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63647. }
  63648. if (parsedTexture.boundingBoxSize) {
  63649. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63650. }
  63651. // Animations
  63652. if (parsedTexture.animations) {
  63653. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63654. var parsedAnimation = parsedTexture.animations[animationIndex];
  63655. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63656. }
  63657. }
  63658. return texture;
  63659. };
  63660. CubeTexture.prototype.clone = function () {
  63661. var _this = this;
  63662. return BABYLON.SerializationHelper.Clone(function () {
  63663. var scene = _this.getScene();
  63664. if (!scene) {
  63665. return _this;
  63666. }
  63667. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63668. }, this);
  63669. };
  63670. __decorate([
  63671. BABYLON.serialize("rotationY")
  63672. ], CubeTexture.prototype, "_rotationY", void 0);
  63673. return CubeTexture;
  63674. }(BABYLON.BaseTexture));
  63675. BABYLON.CubeTexture = CubeTexture;
  63676. })(BABYLON || (BABYLON = {}));
  63677. //# sourceMappingURL=babylon.cubeTexture.js.map
  63678. var BABYLON;
  63679. (function (BABYLON) {
  63680. var RenderTargetTexture = /** @class */ (function (_super) {
  63681. __extends(RenderTargetTexture, _super);
  63682. /**
  63683. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63684. * or used a shadow, depth texture...
  63685. * @param name The friendly name of the texture
  63686. * @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)
  63687. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63688. * @param generateMipMaps True if mip maps need to be generated after render.
  63689. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63690. * @param type The type of the buffer in the RTT (int, half float, float...)
  63691. * @param isCube True if a cube texture needs to be created
  63692. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63693. * @param generateDepthBuffer True to generate a depth buffer
  63694. * @param generateStencilBuffer True to generate a stencil buffer
  63695. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63696. */
  63697. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63698. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63699. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63700. if (isCube === void 0) { isCube = false; }
  63701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63702. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63703. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63704. if (isMulti === void 0) { isMulti = false; }
  63705. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63706. _this.isCube = isCube;
  63707. /**
  63708. * Use this list to define the list of mesh you want to render.
  63709. */
  63710. _this.renderList = new Array();
  63711. _this.renderParticles = true;
  63712. _this.renderSprites = false;
  63713. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63714. _this.ignoreCameraViewport = false;
  63715. // Events
  63716. /**
  63717. * An event triggered when the texture is unbind.
  63718. */
  63719. _this.onBeforeBindObservable = new BABYLON.Observable();
  63720. /**
  63721. * An event triggered when the texture is unbind.
  63722. */
  63723. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63724. /**
  63725. * An event triggered before rendering the texture
  63726. */
  63727. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63728. /**
  63729. * An event triggered after rendering the texture
  63730. */
  63731. _this.onAfterRenderObservable = new BABYLON.Observable();
  63732. /**
  63733. * An event triggered after the texture clear
  63734. */
  63735. _this.onClearObservable = new BABYLON.Observable();
  63736. _this._currentRefreshId = -1;
  63737. _this._refreshRate = 1;
  63738. _this._samples = 1;
  63739. /**
  63740. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63741. * It must define where the camera used to render the texture is set
  63742. */
  63743. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63744. scene = _this.getScene();
  63745. if (!scene) {
  63746. return _this;
  63747. }
  63748. _this._engine = scene.getEngine();
  63749. _this.name = name;
  63750. _this.isRenderTarget = true;
  63751. _this._initialSizeParameter = size;
  63752. _this._processSizeParameter(size);
  63753. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63754. });
  63755. _this._generateMipMaps = generateMipMaps ? true : false;
  63756. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63757. // Rendering groups
  63758. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63759. if (isMulti) {
  63760. return _this;
  63761. }
  63762. _this._renderTargetOptions = {
  63763. generateMipMaps: generateMipMaps,
  63764. type: type,
  63765. samplingMode: samplingMode,
  63766. generateDepthBuffer: generateDepthBuffer,
  63767. generateStencilBuffer: generateStencilBuffer
  63768. };
  63769. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63770. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63771. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63772. }
  63773. if (isCube) {
  63774. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63775. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63776. _this._textureMatrix = BABYLON.Matrix.Identity();
  63777. }
  63778. else {
  63779. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63780. }
  63781. return _this;
  63782. }
  63783. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63784. get: function () {
  63785. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63786. },
  63787. enumerable: true,
  63788. configurable: true
  63789. });
  63790. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63791. get: function () {
  63792. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63793. },
  63794. enumerable: true,
  63795. configurable: true
  63796. });
  63797. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63798. get: function () {
  63799. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63800. },
  63801. enumerable: true,
  63802. configurable: true
  63803. });
  63804. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63805. set: function (callback) {
  63806. if (this._onAfterUnbindObserver) {
  63807. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63808. }
  63809. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63810. },
  63811. enumerable: true,
  63812. configurable: true
  63813. });
  63814. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63815. set: function (callback) {
  63816. if (this._onBeforeRenderObserver) {
  63817. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63818. }
  63819. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63820. },
  63821. enumerable: true,
  63822. configurable: true
  63823. });
  63824. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63825. set: function (callback) {
  63826. if (this._onAfterRenderObserver) {
  63827. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63828. }
  63829. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63830. },
  63831. enumerable: true,
  63832. configurable: true
  63833. });
  63834. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63835. set: function (callback) {
  63836. if (this._onClearObserver) {
  63837. this.onClearObservable.remove(this._onClearObserver);
  63838. }
  63839. this._onClearObserver = this.onClearObservable.add(callback);
  63840. },
  63841. enumerable: true,
  63842. configurable: true
  63843. });
  63844. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63845. get: function () {
  63846. return this._renderTargetOptions;
  63847. },
  63848. enumerable: true,
  63849. configurable: true
  63850. });
  63851. RenderTargetTexture.prototype._onRatioRescale = function () {
  63852. if (this._sizeRatio) {
  63853. this.resize(this._initialSizeParameter);
  63854. }
  63855. };
  63856. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63857. get: function () {
  63858. return this._boundingBoxSize;
  63859. },
  63860. /**
  63861. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63862. * When defined, the cubemap will switch to local mode
  63863. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63864. * @example https://www.babylonjs-playground.com/#RNASML
  63865. */
  63866. set: function (value) {
  63867. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63868. return;
  63869. }
  63870. this._boundingBoxSize = value;
  63871. var scene = this.getScene();
  63872. if (scene) {
  63873. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63874. }
  63875. },
  63876. enumerable: true,
  63877. configurable: true
  63878. });
  63879. /**
  63880. * Creates a depth stencil texture.
  63881. * This is only available in WebGL 2 or with the depth texture extension available.
  63882. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63883. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63884. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63885. */
  63886. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63887. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63888. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63889. if (generateStencil === void 0) { generateStencil = false; }
  63890. if (!this.getScene()) {
  63891. return;
  63892. }
  63893. var engine = this.getScene().getEngine();
  63894. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63895. bilinearFiltering: bilinearFiltering,
  63896. comparisonFunction: comparisonFunction,
  63897. generateStencil: generateStencil,
  63898. isCube: this.isCube
  63899. });
  63900. engine.setFrameBufferDepthStencilTexture(this);
  63901. };
  63902. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63903. if (size.ratio) {
  63904. this._sizeRatio = size.ratio;
  63905. this._size = {
  63906. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63907. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63908. };
  63909. }
  63910. else {
  63911. this._size = size;
  63912. }
  63913. };
  63914. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63915. get: function () {
  63916. return this._samples;
  63917. },
  63918. set: function (value) {
  63919. if (this._samples === value) {
  63920. return;
  63921. }
  63922. var scene = this.getScene();
  63923. if (!scene) {
  63924. return;
  63925. }
  63926. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63927. },
  63928. enumerable: true,
  63929. configurable: true
  63930. });
  63931. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63932. this._currentRefreshId = -1;
  63933. };
  63934. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63935. get: function () {
  63936. return this._refreshRate;
  63937. },
  63938. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63939. set: function (value) {
  63940. this._refreshRate = value;
  63941. this.resetRefreshCounter();
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63947. if (!this._postProcessManager) {
  63948. var scene = this.getScene();
  63949. if (!scene) {
  63950. return;
  63951. }
  63952. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63953. this._postProcesses = new Array();
  63954. }
  63955. this._postProcesses.push(postProcess);
  63956. this._postProcesses[0].autoClear = false;
  63957. };
  63958. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63959. if (!this._postProcesses) {
  63960. return;
  63961. }
  63962. if (dispose) {
  63963. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63964. var postProcess = _a[_i];
  63965. postProcess.dispose();
  63966. }
  63967. }
  63968. this._postProcesses = [];
  63969. };
  63970. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63971. if (!this._postProcesses) {
  63972. return;
  63973. }
  63974. var index = this._postProcesses.indexOf(postProcess);
  63975. if (index === -1) {
  63976. return;
  63977. }
  63978. this._postProcesses.splice(index, 1);
  63979. if (this._postProcesses.length > 0) {
  63980. this._postProcesses[0].autoClear = false;
  63981. }
  63982. };
  63983. RenderTargetTexture.prototype._shouldRender = function () {
  63984. if (this._currentRefreshId === -1) { // At least render once
  63985. this._currentRefreshId = 1;
  63986. return true;
  63987. }
  63988. if (this.refreshRate === this._currentRefreshId) {
  63989. this._currentRefreshId = 1;
  63990. return true;
  63991. }
  63992. this._currentRefreshId++;
  63993. return false;
  63994. };
  63995. RenderTargetTexture.prototype.getRenderSize = function () {
  63996. if (this._size.width) {
  63997. return this._size.width;
  63998. }
  63999. return this._size;
  64000. };
  64001. RenderTargetTexture.prototype.getRenderWidth = function () {
  64002. if (this._size.width) {
  64003. return this._size.width;
  64004. }
  64005. return this._size;
  64006. };
  64007. RenderTargetTexture.prototype.getRenderHeight = function () {
  64008. if (this._size.width) {
  64009. return this._size.height;
  64010. }
  64011. return this._size;
  64012. };
  64013. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64014. get: function () {
  64015. return true;
  64016. },
  64017. enumerable: true,
  64018. configurable: true
  64019. });
  64020. RenderTargetTexture.prototype.scale = function (ratio) {
  64021. var newSize = this.getRenderSize() * ratio;
  64022. this.resize(newSize);
  64023. };
  64024. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64025. if (this.isCube) {
  64026. return this._textureMatrix;
  64027. }
  64028. return _super.prototype.getReflectionTextureMatrix.call(this);
  64029. };
  64030. RenderTargetTexture.prototype.resize = function (size) {
  64031. this.releaseInternalTexture();
  64032. var scene = this.getScene();
  64033. if (!scene) {
  64034. return;
  64035. }
  64036. this._processSizeParameter(size);
  64037. if (this.isCube) {
  64038. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64039. }
  64040. else {
  64041. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64042. }
  64043. };
  64044. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64045. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64046. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64047. var scene = this.getScene();
  64048. if (!scene) {
  64049. return;
  64050. }
  64051. var engine = scene.getEngine();
  64052. if (this.useCameraPostProcesses !== undefined) {
  64053. useCameraPostProcess = this.useCameraPostProcesses;
  64054. }
  64055. if (this._waitingRenderList) {
  64056. this.renderList = [];
  64057. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64058. var id = this._waitingRenderList[index];
  64059. var mesh_1 = scene.getMeshByID(id);
  64060. if (mesh_1) {
  64061. this.renderList.push(mesh_1);
  64062. }
  64063. }
  64064. delete this._waitingRenderList;
  64065. }
  64066. // Is predicate defined?
  64067. if (this.renderListPredicate) {
  64068. if (this.renderList) {
  64069. this.renderList.splice(0); // Clear previous renderList
  64070. }
  64071. else {
  64072. this.renderList = [];
  64073. }
  64074. var scene = this.getScene();
  64075. if (!scene) {
  64076. return;
  64077. }
  64078. var sceneMeshes = scene.meshes;
  64079. for (var index = 0; index < sceneMeshes.length; index++) {
  64080. var mesh = sceneMeshes[index];
  64081. if (this.renderListPredicate(mesh)) {
  64082. this.renderList.push(mesh);
  64083. }
  64084. }
  64085. }
  64086. this.onBeforeBindObservable.notifyObservers(this);
  64087. // Set custom projection.
  64088. // Needs to be before binding to prevent changing the aspect ratio.
  64089. var camera;
  64090. if (this.activeCamera) {
  64091. camera = this.activeCamera;
  64092. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64093. if (this.activeCamera !== scene.activeCamera) {
  64094. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64095. }
  64096. }
  64097. else {
  64098. camera = scene.activeCamera;
  64099. if (camera) {
  64100. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64101. }
  64102. }
  64103. // Prepare renderingManager
  64104. this._renderingManager.reset();
  64105. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64106. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64107. var sceneRenderId = scene.getRenderId();
  64108. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64109. var mesh = currentRenderList[meshIndex];
  64110. if (mesh) {
  64111. if (!mesh.isReady(this.refreshRate === 0)) {
  64112. this.resetRefreshCounter();
  64113. continue;
  64114. }
  64115. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64116. var isMasked = void 0;
  64117. if (!this.renderList && camera) {
  64118. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64119. }
  64120. else {
  64121. isMasked = false;
  64122. }
  64123. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64124. mesh._activate(sceneRenderId);
  64125. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64126. var subMesh = mesh.subMeshes[subIndex];
  64127. scene._activeIndices.addCount(subMesh.indexCount, false);
  64128. this._renderingManager.dispatch(subMesh, mesh);
  64129. }
  64130. }
  64131. }
  64132. }
  64133. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64134. var particleSystem = scene.particleSystems[particleIndex];
  64135. var emitter = particleSystem.emitter;
  64136. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64137. continue;
  64138. }
  64139. if (currentRenderList.indexOf(emitter) >= 0) {
  64140. this._renderingManager.dispatchParticles(particleSystem);
  64141. }
  64142. }
  64143. if (this.isCube) {
  64144. for (var face = 0; face < 6; face++) {
  64145. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64146. scene.incrementRenderId();
  64147. scene.resetCachedMaterial();
  64148. }
  64149. }
  64150. else {
  64151. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64152. }
  64153. this.onAfterUnbindObservable.notifyObservers(this);
  64154. if (scene.activeCamera) {
  64155. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64156. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64157. }
  64158. engine.setViewport(scene.activeCamera.viewport);
  64159. }
  64160. scene.resetCachedMaterial();
  64161. };
  64162. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64163. var minimum = 128;
  64164. var x = renderDimension * scale;
  64165. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64166. // Ensure we don't exceed the render dimension (while staying POT)
  64167. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64168. };
  64169. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64170. var _this = this;
  64171. if (!this._texture) {
  64172. return;
  64173. }
  64174. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64175. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64176. });
  64177. };
  64178. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64179. var scene = this.getScene();
  64180. if (!scene) {
  64181. return;
  64182. }
  64183. var engine = scene.getEngine();
  64184. if (!this._texture) {
  64185. return;
  64186. }
  64187. // Bind
  64188. if (this._postProcessManager) {
  64189. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64190. }
  64191. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64192. if (this._texture) {
  64193. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64194. }
  64195. }
  64196. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64197. // Clear
  64198. if (this.onClearObservable.hasObservers()) {
  64199. this.onClearObservable.notifyObservers(engine);
  64200. }
  64201. else {
  64202. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64203. }
  64204. if (!this._doNotChangeAspectRatio) {
  64205. scene.updateTransformMatrix(true);
  64206. }
  64207. // Render
  64208. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64209. if (this._postProcessManager) {
  64210. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64211. }
  64212. else if (useCameraPostProcess) {
  64213. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64214. }
  64215. if (!this._doNotChangeAspectRatio) {
  64216. scene.updateTransformMatrix(true);
  64217. }
  64218. // Dump ?
  64219. if (dumpForDebug) {
  64220. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64221. }
  64222. // Unbind
  64223. if (!this.isCube || faceIndex === 5) {
  64224. if (this.isCube) {
  64225. if (faceIndex === 5) {
  64226. engine.generateMipMapsForCubemap(this._texture);
  64227. }
  64228. }
  64229. this.unbindFrameBuffer(engine, faceIndex);
  64230. }
  64231. else {
  64232. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64233. }
  64234. };
  64235. /**
  64236. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64237. * This allowed control for front to back rendering or reversly depending of the special needs.
  64238. *
  64239. * @param renderingGroupId The rendering group id corresponding to its index
  64240. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64241. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64242. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64243. */
  64244. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64245. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64246. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64247. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64248. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64249. };
  64250. /**
  64251. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64252. *
  64253. * @param renderingGroupId The rendering group id corresponding to its index
  64254. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64255. */
  64256. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64257. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64258. };
  64259. RenderTargetTexture.prototype.clone = function () {
  64260. var textureSize = this.getSize();
  64261. 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);
  64262. // Base texture
  64263. newTexture.hasAlpha = this.hasAlpha;
  64264. newTexture.level = this.level;
  64265. // RenderTarget Texture
  64266. newTexture.coordinatesMode = this.coordinatesMode;
  64267. if (this.renderList) {
  64268. newTexture.renderList = this.renderList.slice(0);
  64269. }
  64270. return newTexture;
  64271. };
  64272. RenderTargetTexture.prototype.serialize = function () {
  64273. if (!this.name) {
  64274. return null;
  64275. }
  64276. var serializationObject = _super.prototype.serialize.call(this);
  64277. serializationObject.renderTargetSize = this.getRenderSize();
  64278. serializationObject.renderList = [];
  64279. if (this.renderList) {
  64280. for (var index = 0; index < this.renderList.length; index++) {
  64281. serializationObject.renderList.push(this.renderList[index].id);
  64282. }
  64283. }
  64284. return serializationObject;
  64285. };
  64286. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64287. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64288. var objBuffer = this.getInternalTexture();
  64289. var scene = this.getScene();
  64290. if (objBuffer && scene) {
  64291. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64292. }
  64293. };
  64294. RenderTargetTexture.prototype.dispose = function () {
  64295. if (this._postProcessManager) {
  64296. this._postProcessManager.dispose();
  64297. this._postProcessManager = null;
  64298. }
  64299. this.clearPostProcesses(true);
  64300. if (this._resizeObserver) {
  64301. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64302. this._resizeObserver = null;
  64303. }
  64304. this.renderList = null;
  64305. // Remove from custom render targets
  64306. var scene = this.getScene();
  64307. if (!scene) {
  64308. return;
  64309. }
  64310. var index = scene.customRenderTargets.indexOf(this);
  64311. if (index >= 0) {
  64312. scene.customRenderTargets.splice(index, 1);
  64313. }
  64314. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64315. var camera = _a[_i];
  64316. index = camera.customRenderTargets.indexOf(this);
  64317. if (index >= 0) {
  64318. camera.customRenderTargets.splice(index, 1);
  64319. }
  64320. }
  64321. _super.prototype.dispose.call(this);
  64322. };
  64323. RenderTargetTexture.prototype._rebuild = function () {
  64324. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64325. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64326. }
  64327. if (this._postProcessManager) {
  64328. this._postProcessManager._rebuild();
  64329. }
  64330. };
  64331. /**
  64332. * Clear the info related to rendering groups preventing retention point in material dispose.
  64333. */
  64334. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64335. if (this._renderingManager) {
  64336. this._renderingManager.freeRenderingGroups();
  64337. }
  64338. };
  64339. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64340. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64341. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64342. return RenderTargetTexture;
  64343. }(BABYLON.Texture));
  64344. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64345. })(BABYLON || (BABYLON = {}));
  64346. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64347. var BABYLON;
  64348. (function (BABYLON) {
  64349. ;
  64350. var MultiRenderTarget = /** @class */ (function (_super) {
  64351. __extends(MultiRenderTarget, _super);
  64352. function MultiRenderTarget(name, size, count, scene, options) {
  64353. var _this = this;
  64354. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64355. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64356. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64357. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64358. _this._engine = scene.getEngine();
  64359. if (!_this.isSupported) {
  64360. _this.dispose();
  64361. return;
  64362. }
  64363. var types = [];
  64364. var samplingModes = [];
  64365. for (var i = 0; i < count; i++) {
  64366. if (options && options.types && options.types[i] !== undefined) {
  64367. types.push(options.types[i]);
  64368. }
  64369. else {
  64370. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64371. }
  64372. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64373. samplingModes.push(options.samplingModes[i]);
  64374. }
  64375. else {
  64376. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64377. }
  64378. }
  64379. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64380. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64381. _this._size = size;
  64382. _this._multiRenderTargetOptions = {
  64383. samplingModes: samplingModes,
  64384. generateMipMaps: generateMipMaps,
  64385. generateDepthBuffer: generateDepthBuffer,
  64386. generateStencilBuffer: generateStencilBuffer,
  64387. generateDepthTexture: generateDepthTexture,
  64388. types: types,
  64389. textureCount: count
  64390. };
  64391. _this._createInternalTextures();
  64392. _this._createTextures();
  64393. return _this;
  64394. }
  64395. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64396. get: function () {
  64397. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64398. },
  64399. enumerable: true,
  64400. configurable: true
  64401. });
  64402. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64403. get: function () {
  64404. return this._textures;
  64405. },
  64406. enumerable: true,
  64407. configurable: true
  64408. });
  64409. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64410. get: function () {
  64411. return this._textures[this._textures.length - 1];
  64412. },
  64413. enumerable: true,
  64414. configurable: true
  64415. });
  64416. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64417. set: function (wrap) {
  64418. if (this._textures) {
  64419. for (var i = 0; i < this._textures.length; i++) {
  64420. this._textures[i].wrapU = wrap;
  64421. }
  64422. }
  64423. },
  64424. enumerable: true,
  64425. configurable: true
  64426. });
  64427. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64428. set: function (wrap) {
  64429. if (this._textures) {
  64430. for (var i = 0; i < this._textures.length; i++) {
  64431. this._textures[i].wrapV = wrap;
  64432. }
  64433. }
  64434. },
  64435. enumerable: true,
  64436. configurable: true
  64437. });
  64438. MultiRenderTarget.prototype._rebuild = function () {
  64439. this.releaseInternalTextures();
  64440. this._createInternalTextures();
  64441. for (var i = 0; i < this._internalTextures.length; i++) {
  64442. var texture = this._textures[i];
  64443. texture._texture = this._internalTextures[i];
  64444. }
  64445. // Keeps references to frame buffer and stencil/depth buffer
  64446. this._texture = this._internalTextures[0];
  64447. };
  64448. MultiRenderTarget.prototype._createInternalTextures = function () {
  64449. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64450. };
  64451. MultiRenderTarget.prototype._createTextures = function () {
  64452. this._textures = [];
  64453. for (var i = 0; i < this._internalTextures.length; i++) {
  64454. var texture = new BABYLON.Texture(null, this.getScene());
  64455. texture._texture = this._internalTextures[i];
  64456. this._textures.push(texture);
  64457. }
  64458. // Keeps references to frame buffer and stencil/depth buffer
  64459. this._texture = this._internalTextures[0];
  64460. };
  64461. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64462. get: function () {
  64463. return this._samples;
  64464. },
  64465. set: function (value) {
  64466. if (this._samples === value) {
  64467. return;
  64468. }
  64469. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64470. },
  64471. enumerable: true,
  64472. configurable: true
  64473. });
  64474. MultiRenderTarget.prototype.resize = function (size) {
  64475. this.releaseInternalTextures();
  64476. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64477. this._createInternalTextures();
  64478. };
  64479. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64480. var _this = this;
  64481. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64482. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64483. });
  64484. };
  64485. MultiRenderTarget.prototype.dispose = function () {
  64486. this.releaseInternalTextures();
  64487. _super.prototype.dispose.call(this);
  64488. };
  64489. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64490. if (!this._internalTextures) {
  64491. return;
  64492. }
  64493. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64494. if (this._internalTextures[i] !== undefined) {
  64495. this._internalTextures[i].dispose();
  64496. this._internalTextures.splice(i, 1);
  64497. }
  64498. }
  64499. };
  64500. return MultiRenderTarget;
  64501. }(BABYLON.RenderTargetTexture));
  64502. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64503. })(BABYLON || (BABYLON = {}));
  64504. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64505. var BABYLON;
  64506. (function (BABYLON) {
  64507. var MirrorTexture = /** @class */ (function (_super) {
  64508. __extends(MirrorTexture, _super);
  64509. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64510. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64511. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64512. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64513. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64514. _this.scene = scene;
  64515. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64516. _this._transformMatrix = BABYLON.Matrix.Zero();
  64517. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64518. _this._adaptiveBlurKernel = 0;
  64519. _this._blurKernelX = 0;
  64520. _this._blurKernelY = 0;
  64521. _this._blurRatio = 1.0;
  64522. _this.ignoreCameraViewport = true;
  64523. _this._updateGammaSpace();
  64524. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64525. _this._updateGammaSpace;
  64526. });
  64527. _this.onBeforeRenderObservable.add(function () {
  64528. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64529. _this._savedViewMatrix = scene.getViewMatrix();
  64530. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64531. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64532. scene.clipPlane = _this.mirrorPlane;
  64533. scene.getEngine().cullBackFaces = false;
  64534. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64535. });
  64536. _this.onAfterRenderObservable.add(function () {
  64537. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64538. scene.getEngine().cullBackFaces = true;
  64539. scene._mirroredCameraPosition = null;
  64540. delete scene.clipPlane;
  64541. });
  64542. return _this;
  64543. }
  64544. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64545. get: function () {
  64546. return this._blurRatio;
  64547. },
  64548. set: function (value) {
  64549. if (this._blurRatio === value) {
  64550. return;
  64551. }
  64552. this._blurRatio = value;
  64553. this._preparePostProcesses();
  64554. },
  64555. enumerable: true,
  64556. configurable: true
  64557. });
  64558. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64559. set: function (value) {
  64560. this._adaptiveBlurKernel = value;
  64561. this._autoComputeBlurKernel();
  64562. },
  64563. enumerable: true,
  64564. configurable: true
  64565. });
  64566. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64567. set: function (value) {
  64568. this.blurKernelX = value;
  64569. this.blurKernelY = value;
  64570. },
  64571. enumerable: true,
  64572. configurable: true
  64573. });
  64574. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64575. get: function () {
  64576. return this._blurKernelX;
  64577. },
  64578. set: function (value) {
  64579. if (this._blurKernelX === value) {
  64580. return;
  64581. }
  64582. this._blurKernelX = value;
  64583. this._preparePostProcesses();
  64584. },
  64585. enumerable: true,
  64586. configurable: true
  64587. });
  64588. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64589. get: function () {
  64590. return this._blurKernelY;
  64591. },
  64592. set: function (value) {
  64593. if (this._blurKernelY === value) {
  64594. return;
  64595. }
  64596. this._blurKernelY = value;
  64597. this._preparePostProcesses();
  64598. },
  64599. enumerable: true,
  64600. configurable: true
  64601. });
  64602. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64603. var engine = this.getScene().getEngine();
  64604. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64605. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64606. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64607. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64608. };
  64609. MirrorTexture.prototype._onRatioRescale = function () {
  64610. if (this._sizeRatio) {
  64611. this.resize(this._initialSizeParameter);
  64612. if (!this._adaptiveBlurKernel) {
  64613. this._preparePostProcesses();
  64614. }
  64615. }
  64616. if (this._adaptiveBlurKernel) {
  64617. this._autoComputeBlurKernel();
  64618. }
  64619. };
  64620. MirrorTexture.prototype._updateGammaSpace = function () {
  64621. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64622. };
  64623. MirrorTexture.prototype._preparePostProcesses = function () {
  64624. this.clearPostProcesses(true);
  64625. if (this._blurKernelX && this._blurKernelY) {
  64626. var engine = this.getScene().getEngine();
  64627. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64628. 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);
  64629. this._blurX.autoClear = false;
  64630. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64631. this._blurX.inputTexture = this._texture;
  64632. }
  64633. else {
  64634. this._blurX.alwaysForcePOT = true;
  64635. }
  64636. 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);
  64637. this._blurY.autoClear = false;
  64638. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64639. this.addPostProcess(this._blurX);
  64640. this.addPostProcess(this._blurY);
  64641. }
  64642. else {
  64643. if (this._blurY) {
  64644. this.removePostProcess(this._blurY);
  64645. this._blurY.dispose();
  64646. this._blurY = null;
  64647. }
  64648. if (this._blurX) {
  64649. this.removePostProcess(this._blurX);
  64650. this._blurX.dispose();
  64651. this._blurX = null;
  64652. }
  64653. }
  64654. };
  64655. MirrorTexture.prototype.clone = function () {
  64656. var scene = this.getScene();
  64657. if (!scene) {
  64658. return this;
  64659. }
  64660. var textureSize = this.getSize();
  64661. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64662. // Base texture
  64663. newTexture.hasAlpha = this.hasAlpha;
  64664. newTexture.level = this.level;
  64665. // Mirror Texture
  64666. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64667. if (this.renderList) {
  64668. newTexture.renderList = this.renderList.slice(0);
  64669. }
  64670. return newTexture;
  64671. };
  64672. MirrorTexture.prototype.serialize = function () {
  64673. if (!this.name) {
  64674. return null;
  64675. }
  64676. var serializationObject = _super.prototype.serialize.call(this);
  64677. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64678. return serializationObject;
  64679. };
  64680. MirrorTexture.prototype.dispose = function () {
  64681. _super.prototype.dispose.call(this);
  64682. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64683. };
  64684. return MirrorTexture;
  64685. }(BABYLON.RenderTargetTexture));
  64686. BABYLON.MirrorTexture = MirrorTexture;
  64687. })(BABYLON || (BABYLON = {}));
  64688. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64689. var BABYLON;
  64690. (function (BABYLON) {
  64691. /**
  64692. * Creates a refraction texture used by refraction channel of the standard material.
  64693. * @param name the texture name
  64694. * @param size size of the underlying texture
  64695. * @param scene root scene
  64696. */
  64697. var RefractionTexture = /** @class */ (function (_super) {
  64698. __extends(RefractionTexture, _super);
  64699. function RefractionTexture(name, size, scene, generateMipMaps) {
  64700. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64701. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64702. _this.depth = 2.0;
  64703. _this.onBeforeRenderObservable.add(function () {
  64704. scene.clipPlane = _this.refractionPlane;
  64705. });
  64706. _this.onAfterRenderObservable.add(function () {
  64707. delete scene.clipPlane;
  64708. });
  64709. return _this;
  64710. }
  64711. RefractionTexture.prototype.clone = function () {
  64712. var scene = this.getScene();
  64713. if (!scene) {
  64714. return this;
  64715. }
  64716. var textureSize = this.getSize();
  64717. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64718. // Base texture
  64719. newTexture.hasAlpha = this.hasAlpha;
  64720. newTexture.level = this.level;
  64721. // Refraction Texture
  64722. newTexture.refractionPlane = this.refractionPlane.clone();
  64723. if (this.renderList) {
  64724. newTexture.renderList = this.renderList.slice(0);
  64725. }
  64726. newTexture.depth = this.depth;
  64727. return newTexture;
  64728. };
  64729. RefractionTexture.prototype.serialize = function () {
  64730. if (!this.name) {
  64731. return null;
  64732. }
  64733. var serializationObject = _super.prototype.serialize.call(this);
  64734. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64735. serializationObject.depth = this.depth;
  64736. return serializationObject;
  64737. };
  64738. return RefractionTexture;
  64739. }(BABYLON.RenderTargetTexture));
  64740. BABYLON.RefractionTexture = RefractionTexture;
  64741. })(BABYLON || (BABYLON = {}));
  64742. //# sourceMappingURL=babylon.refractionTexture.js.map
  64743. var BABYLON;
  64744. (function (BABYLON) {
  64745. /**
  64746. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64747. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64748. */
  64749. var DynamicTexture = /** @class */ (function (_super) {
  64750. __extends(DynamicTexture, _super);
  64751. /**
  64752. * Creates a {BABYLON.DynamicTexture}
  64753. * @param name defines the name of the texture
  64754. * @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
  64755. * @param scene defines the scene where you want the texture
  64756. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64757. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64758. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64759. */
  64760. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64761. if (scene === void 0) { scene = null; }
  64762. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64763. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64764. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64765. _this.name = name;
  64766. _this._engine = _this.getScene().getEngine();
  64767. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64768. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64769. _this._generateMipMaps = generateMipMaps;
  64770. if (options.getContext) {
  64771. _this._canvas = options;
  64772. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64773. }
  64774. else {
  64775. _this._canvas = document.createElement("canvas");
  64776. if (options.width || options.width === 0) {
  64777. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64778. }
  64779. else {
  64780. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64781. }
  64782. }
  64783. var textureSize = _this.getSize();
  64784. _this._canvas.width = textureSize.width;
  64785. _this._canvas.height = textureSize.height;
  64786. _this._context = _this._canvas.getContext("2d");
  64787. return _this;
  64788. }
  64789. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64790. /**
  64791. * Gets the current state of canRescale
  64792. */
  64793. get: function () {
  64794. return true;
  64795. },
  64796. enumerable: true,
  64797. configurable: true
  64798. });
  64799. DynamicTexture.prototype._recreate = function (textureSize) {
  64800. this._canvas.width = textureSize.width;
  64801. this._canvas.height = textureSize.height;
  64802. this.releaseInternalTexture();
  64803. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64804. };
  64805. /**
  64806. * Scales the texture
  64807. * @param ratio the scale factor to apply to both width and height
  64808. */
  64809. DynamicTexture.prototype.scale = function (ratio) {
  64810. var textureSize = this.getSize();
  64811. textureSize.width *= ratio;
  64812. textureSize.height *= ratio;
  64813. this._recreate(textureSize);
  64814. };
  64815. /**
  64816. * Resizes the texture
  64817. * @param width the new width
  64818. * @param height the new height
  64819. */
  64820. DynamicTexture.prototype.scaleTo = function (width, height) {
  64821. var textureSize = this.getSize();
  64822. textureSize.width = width;
  64823. textureSize.height = height;
  64824. this._recreate(textureSize);
  64825. };
  64826. /**
  64827. * Gets the context of the canvas used by the texture
  64828. * @returns the canvas context of the dynamic texture
  64829. */
  64830. DynamicTexture.prototype.getContext = function () {
  64831. return this._context;
  64832. };
  64833. /**
  64834. * Clears the texture
  64835. */
  64836. DynamicTexture.prototype.clear = function () {
  64837. var size = this.getSize();
  64838. this._context.fillRect(0, 0, size.width, size.height);
  64839. };
  64840. /**
  64841. * Updates the texture
  64842. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64843. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64844. */
  64845. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64846. if (premulAlpha === void 0) { premulAlpha = false; }
  64847. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64848. };
  64849. /**
  64850. * Draws text onto the texture
  64851. * @param text defines the text to be drawn
  64852. * @param x defines the placement of the text from the left
  64853. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64854. * @param font defines the font to be used with font-style, font-size, font-name
  64855. * @param color defines the color used for the text
  64856. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64857. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64858. * @param update defines whether texture is immediately update (default is true)
  64859. */
  64860. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64861. if (update === void 0) { update = true; }
  64862. var size = this.getSize();
  64863. if (clearColor) {
  64864. this._context.fillStyle = clearColor;
  64865. this._context.fillRect(0, 0, size.width, size.height);
  64866. }
  64867. this._context.font = font;
  64868. if (x === null || x === undefined) {
  64869. var textSize = this._context.measureText(text);
  64870. x = (size.width - textSize.width) / 2;
  64871. }
  64872. if (y === null || y === undefined) {
  64873. var fontSize = parseInt((font.replace(/\D/g, '')));
  64874. y = (size.height / 2) + (fontSize / 3.65);
  64875. }
  64876. this._context.fillStyle = color;
  64877. this._context.fillText(text, x, y);
  64878. if (update) {
  64879. this.update(invertY);
  64880. }
  64881. };
  64882. /**
  64883. * Clones the texture
  64884. * @returns the clone of the texture.
  64885. */
  64886. DynamicTexture.prototype.clone = function () {
  64887. var scene = this.getScene();
  64888. if (!scene) {
  64889. return this;
  64890. }
  64891. var textureSize = this.getSize();
  64892. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64893. // Base texture
  64894. newTexture.hasAlpha = this.hasAlpha;
  64895. newTexture.level = this.level;
  64896. // Dynamic Texture
  64897. newTexture.wrapU = this.wrapU;
  64898. newTexture.wrapV = this.wrapV;
  64899. return newTexture;
  64900. };
  64901. /** @hidden */
  64902. DynamicTexture.prototype._rebuild = function () {
  64903. this.update();
  64904. };
  64905. return DynamicTexture;
  64906. }(BABYLON.Texture));
  64907. BABYLON.DynamicTexture = DynamicTexture;
  64908. })(BABYLON || (BABYLON = {}));
  64909. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64910. var BABYLON;
  64911. (function (BABYLON) {
  64912. var VideoTexture = /** @class */ (function (_super) {
  64913. __extends(VideoTexture, _super);
  64914. /**
  64915. * Creates a video texture.
  64916. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64917. * @param {string | null} name optional name, will detect from video source, if not defined
  64918. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64919. * @param {BABYLON.Scene} scene is obviously the current scene.
  64920. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64921. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64922. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64923. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64924. */
  64925. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64926. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64927. if (invertY === void 0) { invertY = false; }
  64928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64929. if (settings === void 0) { settings = {
  64930. autoPlay: true,
  64931. loop: true,
  64932. autoUpdateTexture: true,
  64933. }; }
  64934. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64935. _this._stillImageCaptured = false;
  64936. _this._createInternalTexture = function () {
  64937. if (_this._texture != null) {
  64938. return;
  64939. }
  64940. if (!_this._engine.needPOTTextures ||
  64941. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64942. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64943. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64944. }
  64945. else {
  64946. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64947. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64948. _this._generateMipMaps = false;
  64949. }
  64950. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64951. if (!_this.video.autoplay) {
  64952. var oldHandler_1 = _this.video.onplaying;
  64953. _this.video.onplaying = function () {
  64954. _this.video.onplaying = oldHandler_1;
  64955. _this._texture.isReady = true;
  64956. _this._updateInternalTexture();
  64957. _this.video.pause();
  64958. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64959. _this.onLoadObservable.notifyObservers(_this);
  64960. }
  64961. };
  64962. _this.video.play();
  64963. }
  64964. else {
  64965. _this._texture.isReady = true;
  64966. _this._updateInternalTexture();
  64967. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64968. _this.onLoadObservable.notifyObservers(_this);
  64969. }
  64970. }
  64971. };
  64972. _this.reset = function () {
  64973. if (_this._texture == null) {
  64974. return;
  64975. }
  64976. _this._texture.dispose();
  64977. _this._texture = null;
  64978. };
  64979. _this._updateInternalTexture = function (e) {
  64980. if (_this._texture == null || !_this._texture.isReady) {
  64981. return;
  64982. }
  64983. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64984. return;
  64985. }
  64986. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64987. };
  64988. _this._engine = _this.getScene().getEngine();
  64989. _this._generateMipMaps = generateMipMaps;
  64990. _this._samplingMode = samplingMode;
  64991. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64992. _this.name = name || _this._getName(src);
  64993. _this.video = _this._getVideo(src);
  64994. if (settings.autoPlay !== undefined) {
  64995. _this.video.autoplay = settings.autoPlay;
  64996. }
  64997. if (settings.loop !== undefined) {
  64998. _this.video.loop = settings.loop;
  64999. }
  65000. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65001. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65002. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65003. _this.video.addEventListener("emptied", _this.reset);
  65004. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65005. _this._createInternalTexture();
  65006. }
  65007. return _this;
  65008. }
  65009. VideoTexture.prototype._getName = function (src) {
  65010. if (src instanceof HTMLVideoElement) {
  65011. return src.currentSrc;
  65012. }
  65013. if (typeof src === "object") {
  65014. return src.toString();
  65015. }
  65016. return src;
  65017. };
  65018. ;
  65019. VideoTexture.prototype._getVideo = function (src) {
  65020. if (src instanceof HTMLVideoElement) {
  65021. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65022. return src;
  65023. }
  65024. var video = document.createElement("video");
  65025. if (typeof src === "string") {
  65026. BABYLON.Tools.SetCorsBehavior(src, video);
  65027. video.src = src;
  65028. }
  65029. else {
  65030. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65031. src.forEach(function (url) {
  65032. var source = document.createElement("source");
  65033. source.src = url;
  65034. video.appendChild(source);
  65035. });
  65036. }
  65037. return video;
  65038. };
  65039. ;
  65040. /**
  65041. * Internal method to initiate `update`.
  65042. */
  65043. VideoTexture.prototype._rebuild = function () {
  65044. this.update();
  65045. };
  65046. /**
  65047. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65048. */
  65049. VideoTexture.prototype.update = function () {
  65050. if (!this.autoUpdateTexture) {
  65051. // Expecting user to call `updateTexture` manually
  65052. return;
  65053. }
  65054. this.updateTexture(true);
  65055. };
  65056. /**
  65057. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65058. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65059. */
  65060. VideoTexture.prototype.updateTexture = function (isVisible) {
  65061. if (!isVisible) {
  65062. return;
  65063. }
  65064. if (this.video.paused && this._stillImageCaptured) {
  65065. return;
  65066. }
  65067. this._stillImageCaptured = true;
  65068. this._updateInternalTexture();
  65069. };
  65070. /**
  65071. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65072. * @param url New url.
  65073. */
  65074. VideoTexture.prototype.updateURL = function (url) {
  65075. this.video.src = url;
  65076. };
  65077. VideoTexture.prototype.dispose = function () {
  65078. _super.prototype.dispose.call(this);
  65079. this.video.removeEventListener("canplay", this._createInternalTexture);
  65080. this.video.removeEventListener("paused", this._updateInternalTexture);
  65081. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65082. this.video.removeEventListener("emptied", this.reset);
  65083. this.video.pause();
  65084. };
  65085. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65086. var video = document.createElement("video");
  65087. var constraintsDeviceId;
  65088. if (constraints && constraints.deviceId) {
  65089. constraintsDeviceId = {
  65090. exact: constraints.deviceId,
  65091. };
  65092. }
  65093. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65094. if (navigator.mediaDevices) {
  65095. navigator.mediaDevices.getUserMedia({ video: constraints })
  65096. .then(function (stream) {
  65097. if (video.mozSrcObject !== undefined) {
  65098. // hack for Firefox < 19
  65099. video.mozSrcObject = stream;
  65100. }
  65101. else {
  65102. video.srcObject = stream;
  65103. }
  65104. var onPlaying = function () {
  65105. if (onReady) {
  65106. onReady(new VideoTexture("video", video, scene, true, true));
  65107. }
  65108. video.removeEventListener("playing", onPlaying);
  65109. };
  65110. video.addEventListener("playing", onPlaying);
  65111. video.play();
  65112. })
  65113. .catch(function (err) {
  65114. BABYLON.Tools.Error(err.name);
  65115. });
  65116. }
  65117. else {
  65118. navigator.getUserMedia =
  65119. navigator.getUserMedia ||
  65120. navigator.webkitGetUserMedia ||
  65121. navigator.mozGetUserMedia ||
  65122. navigator.msGetUserMedia;
  65123. if (navigator.getUserMedia) {
  65124. navigator.getUserMedia({
  65125. video: {
  65126. deviceId: constraintsDeviceId,
  65127. width: {
  65128. min: (constraints && constraints.minWidth) || 256,
  65129. max: (constraints && constraints.maxWidth) || 640,
  65130. },
  65131. height: {
  65132. min: (constraints && constraints.minHeight) || 256,
  65133. max: (constraints && constraints.maxHeight) || 480,
  65134. },
  65135. },
  65136. }, function (stream) {
  65137. if (video.mozSrcObject !== undefined) {
  65138. // hack for Firefox < 19
  65139. video.mozSrcObject = stream;
  65140. }
  65141. else {
  65142. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65143. }
  65144. video.play();
  65145. if (onReady) {
  65146. onReady(new VideoTexture("video", video, scene, true, true));
  65147. }
  65148. }, function (e) {
  65149. BABYLON.Tools.Error(e.name);
  65150. });
  65151. }
  65152. }
  65153. };
  65154. return VideoTexture;
  65155. }(BABYLON.Texture));
  65156. BABYLON.VideoTexture = VideoTexture;
  65157. })(BABYLON || (BABYLON = {}));
  65158. //# sourceMappingURL=babylon.videoTexture.js.map
  65159. var BABYLON;
  65160. (function (BABYLON) {
  65161. var RawTexture = /** @class */ (function (_super) {
  65162. __extends(RawTexture, _super);
  65163. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65164. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65165. if (invertY === void 0) { invertY = false; }
  65166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65167. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65168. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65169. _this.format = format;
  65170. _this._engine = scene.getEngine();
  65171. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65172. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65173. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65174. return _this;
  65175. }
  65176. RawTexture.prototype.update = function (data) {
  65177. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65178. };
  65179. // Statics
  65180. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65181. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65182. if (invertY === void 0) { invertY = false; }
  65183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65184. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65185. };
  65186. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65187. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65188. if (invertY === void 0) { invertY = false; }
  65189. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65190. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65191. };
  65192. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65193. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65194. if (invertY === void 0) { invertY = false; }
  65195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65196. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65197. };
  65198. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65199. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65200. if (invertY === void 0) { invertY = false; }
  65201. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65202. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65203. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65204. };
  65205. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65206. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65207. if (invertY === void 0) { invertY = false; }
  65208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65209. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65210. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65211. };
  65212. return RawTexture;
  65213. }(BABYLON.Texture));
  65214. BABYLON.RawTexture = RawTexture;
  65215. })(BABYLON || (BABYLON = {}));
  65216. //# sourceMappingURL=babylon.rawTexture.js.map
  65217. var BABYLON;
  65218. (function (BABYLON) {
  65219. /**
  65220. * Class used to store 3D textures containing user data
  65221. */
  65222. var RawTexture3D = /** @class */ (function (_super) {
  65223. __extends(RawTexture3D, _super);
  65224. /**
  65225. * Create a new RawTexture3D
  65226. * @param data defines the data of the texture
  65227. * @param width defines the width of the texture
  65228. * @param height defines the height of the texture
  65229. * @param depth defines the depth of the texture
  65230. * @param format defines the texture format to use
  65231. * @param scene defines the hosting scene
  65232. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65233. * @param invertY defines if texture must be stored with Y axis inverted
  65234. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65235. */
  65236. function RawTexture3D(data, width, height, depth,
  65237. /** Gets or sets the texture format to use*/
  65238. format, scene, generateMipMaps, invertY, samplingMode) {
  65239. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65240. if (invertY === void 0) { invertY = false; }
  65241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65242. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65243. _this.format = format;
  65244. _this._engine = scene.getEngine();
  65245. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  65246. _this.is3D = true;
  65247. return _this;
  65248. }
  65249. /**
  65250. * Update the texture with new data
  65251. * @param data defines the data to store in the texture
  65252. */
  65253. RawTexture3D.prototype.update = function (data) {
  65254. if (!this._texture) {
  65255. return;
  65256. }
  65257. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  65258. };
  65259. return RawTexture3D;
  65260. }(BABYLON.Texture));
  65261. BABYLON.RawTexture3D = RawTexture3D;
  65262. })(BABYLON || (BABYLON = {}));
  65263. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65264. var BABYLON;
  65265. (function (BABYLON) {
  65266. /**
  65267. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65268. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65269. */
  65270. var PostProcess = /** @class */ (function () {
  65271. /**
  65272. * Creates a new instance PostProcess
  65273. * @param name The name of the PostProcess.
  65274. * @param fragmentUrl The url of the fragment shader to be used.
  65275. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65276. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65277. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65278. * @param camera The camera to apply the render pass to.
  65279. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65280. * @param engine The engine which the post process will be applied. (default: current engine)
  65281. * @param reusable If the post process can be reused on the same frame. (default: false)
  65282. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65283. * @param textureType Type of textures used when performing the post process. (default: 0)
  65284. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65285. * @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
  65286. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65287. */
  65288. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65290. if (defines === void 0) { defines = null; }
  65291. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65292. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65293. if (blockCompilation === void 0) { blockCompilation = false; }
  65294. this.name = name;
  65295. /**
  65296. * Width of the texture to apply the post process on
  65297. */
  65298. this.width = -1;
  65299. /**
  65300. * Height of the texture to apply the post process on
  65301. */
  65302. this.height = -1;
  65303. /**
  65304. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65305. */
  65306. this._outputTexture = null;
  65307. /**
  65308. * If the buffer needs to be cleared before applying the post process. (default: true)
  65309. * Should be set to false if shader will overwrite all previous pixels.
  65310. */
  65311. this.autoClear = true;
  65312. /**
  65313. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65314. */
  65315. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65316. /**
  65317. * Animations to be used for the post processing
  65318. */
  65319. this.animations = new Array();
  65320. /**
  65321. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65322. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65323. */
  65324. this.enablePixelPerfectMode = false;
  65325. /**
  65326. * Force the postprocess to be applied without taking in account viewport
  65327. */
  65328. this.forceFullscreenViewport = true;
  65329. /**
  65330. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65331. */
  65332. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65333. /**
  65334. * Force textures to be a power of two (default: false)
  65335. */
  65336. this.alwaysForcePOT = false;
  65337. /**
  65338. * Number of sample textures (default: 1)
  65339. */
  65340. this.samples = 1;
  65341. /**
  65342. * Modify the scale of the post process to be the same as the viewport (default: false)
  65343. */
  65344. this.adaptScaleToCurrentViewport = false;
  65345. this._reusable = false;
  65346. /**
  65347. * Smart array of input and output textures for the post process.
  65348. */
  65349. this._textures = new BABYLON.SmartArray(2);
  65350. /**
  65351. * The index in _textures that corresponds to the output texture.
  65352. */
  65353. this._currentRenderTextureInd = 0;
  65354. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65355. this._texelSize = BABYLON.Vector2.Zero();
  65356. // Events
  65357. /**
  65358. * An event triggered when the postprocess is activated.
  65359. */
  65360. this.onActivateObservable = new BABYLON.Observable();
  65361. /**
  65362. * An event triggered when the postprocess changes its size.
  65363. */
  65364. this.onSizeChangedObservable = new BABYLON.Observable();
  65365. /**
  65366. * An event triggered when the postprocess applies its effect.
  65367. */
  65368. this.onApplyObservable = new BABYLON.Observable();
  65369. /**
  65370. * An event triggered before rendering the postprocess
  65371. */
  65372. this.onBeforeRenderObservable = new BABYLON.Observable();
  65373. /**
  65374. * An event triggered after rendering the postprocess
  65375. */
  65376. this.onAfterRenderObservable = new BABYLON.Observable();
  65377. if (camera != null) {
  65378. this._camera = camera;
  65379. this._scene = camera.getScene();
  65380. camera.attachPostProcess(this);
  65381. this._engine = this._scene.getEngine();
  65382. this._scene.postProcesses.push(this);
  65383. }
  65384. else if (engine) {
  65385. this._engine = engine;
  65386. this._engine.postProcesses.push(this);
  65387. }
  65388. this._options = options;
  65389. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65390. this._reusable = reusable || false;
  65391. this._textureType = textureType;
  65392. this._samplers = samplers || [];
  65393. this._samplers.push("textureSampler");
  65394. this._fragmentUrl = fragmentUrl;
  65395. this._vertexUrl = vertexUrl;
  65396. this._parameters = parameters || [];
  65397. this._parameters.push("scale");
  65398. this._indexParameters = indexParameters;
  65399. if (!blockCompilation) {
  65400. this.updateEffect(defines);
  65401. }
  65402. }
  65403. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65404. /**
  65405. * A function that is added to the onActivateObservable
  65406. */
  65407. set: function (callback) {
  65408. if (this._onActivateObserver) {
  65409. this.onActivateObservable.remove(this._onActivateObserver);
  65410. }
  65411. if (callback) {
  65412. this._onActivateObserver = this.onActivateObservable.add(callback);
  65413. }
  65414. },
  65415. enumerable: true,
  65416. configurable: true
  65417. });
  65418. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65419. /**
  65420. * A function that is added to the onSizeChangedObservable
  65421. */
  65422. set: function (callback) {
  65423. if (this._onSizeChangedObserver) {
  65424. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65425. }
  65426. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65427. },
  65428. enumerable: true,
  65429. configurable: true
  65430. });
  65431. Object.defineProperty(PostProcess.prototype, "onApply", {
  65432. /**
  65433. * A function that is added to the onApplyObservable
  65434. */
  65435. set: function (callback) {
  65436. if (this._onApplyObserver) {
  65437. this.onApplyObservable.remove(this._onApplyObserver);
  65438. }
  65439. this._onApplyObserver = this.onApplyObservable.add(callback);
  65440. },
  65441. enumerable: true,
  65442. configurable: true
  65443. });
  65444. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65445. /**
  65446. * A function that is added to the onBeforeRenderObservable
  65447. */
  65448. set: function (callback) {
  65449. if (this._onBeforeRenderObserver) {
  65450. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65451. }
  65452. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65453. },
  65454. enumerable: true,
  65455. configurable: true
  65456. });
  65457. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65458. /**
  65459. * A function that is added to the onAfterRenderObservable
  65460. */
  65461. set: function (callback) {
  65462. if (this._onAfterRenderObserver) {
  65463. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65464. }
  65465. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65466. },
  65467. enumerable: true,
  65468. configurable: true
  65469. });
  65470. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65471. /**
  65472. * 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
  65473. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65474. */
  65475. get: function () {
  65476. return this._textures.data[this._currentRenderTextureInd];
  65477. },
  65478. set: function (value) {
  65479. this._forcedOutputTexture = value;
  65480. },
  65481. enumerable: true,
  65482. configurable: true
  65483. });
  65484. /**
  65485. * Gets the camera which post process is applied to.
  65486. * @returns The camera the post process is applied to.
  65487. */
  65488. PostProcess.prototype.getCamera = function () {
  65489. return this._camera;
  65490. };
  65491. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65492. /**
  65493. * Gets the texel size of the postprocess.
  65494. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65495. */
  65496. get: function () {
  65497. if (this._shareOutputWithPostProcess) {
  65498. return this._shareOutputWithPostProcess.texelSize;
  65499. }
  65500. if (this._forcedOutputTexture) {
  65501. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65502. }
  65503. return this._texelSize;
  65504. },
  65505. enumerable: true,
  65506. configurable: true
  65507. });
  65508. /**
  65509. * Gets the engine which this post process belongs to.
  65510. * @returns The engine the post process was enabled with.
  65511. */
  65512. PostProcess.prototype.getEngine = function () {
  65513. return this._engine;
  65514. };
  65515. /**
  65516. * The effect that is created when initializing the post process.
  65517. * @returns The created effect corrisponding the the postprocess.
  65518. */
  65519. PostProcess.prototype.getEffect = function () {
  65520. return this._effect;
  65521. };
  65522. /**
  65523. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65524. * @param postProcess The post process to share the output with.
  65525. * @returns This post process.
  65526. */
  65527. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65528. this._disposeTextures();
  65529. this._shareOutputWithPostProcess = postProcess;
  65530. return this;
  65531. };
  65532. /**
  65533. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65534. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65535. */
  65536. PostProcess.prototype.useOwnOutput = function () {
  65537. if (this._textures.length == 0) {
  65538. this._textures = new BABYLON.SmartArray(2);
  65539. }
  65540. this._shareOutputWithPostProcess = null;
  65541. };
  65542. /**
  65543. * Updates the effect with the current post process compile time values and recompiles the shader.
  65544. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65545. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65546. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65547. * @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
  65548. * @param onCompiled Called when the shader has been compiled.
  65549. * @param onError Called if there is an error when compiling a shader.
  65550. */
  65551. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65552. if (defines === void 0) { defines = null; }
  65553. if (uniforms === void 0) { uniforms = null; }
  65554. if (samplers === void 0) { samplers = null; }
  65555. 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);
  65556. };
  65557. /**
  65558. * The post process is reusable if it can be used multiple times within one frame.
  65559. * @returns If the post process is reusable
  65560. */
  65561. PostProcess.prototype.isReusable = function () {
  65562. return this._reusable;
  65563. };
  65564. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65565. PostProcess.prototype.markTextureDirty = function () {
  65566. this.width = -1;
  65567. };
  65568. /**
  65569. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65570. * 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.
  65571. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65572. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65573. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65574. * @returns The target texture that was bound to be written to.
  65575. */
  65576. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65577. var _this = this;
  65578. if (sourceTexture === void 0) { sourceTexture = null; }
  65579. camera = camera || this._camera;
  65580. var scene = camera.getScene();
  65581. var engine = scene.getEngine();
  65582. var maxSize = engine.getCaps().maxTextureSize;
  65583. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65584. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65585. // 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
  65586. var webVRCamera = camera.parent;
  65587. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65588. requiredWidth /= 2;
  65589. }
  65590. var desiredWidth = (this._options.width || requiredWidth);
  65591. var desiredHeight = this._options.height || requiredHeight;
  65592. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65593. if (this.adaptScaleToCurrentViewport) {
  65594. var currentViewport = engine.currentViewport;
  65595. if (currentViewport) {
  65596. desiredWidth *= currentViewport.width;
  65597. desiredHeight *= currentViewport.height;
  65598. }
  65599. }
  65600. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65601. if (!this._options.width) {
  65602. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65603. }
  65604. if (!this._options.height) {
  65605. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65606. }
  65607. }
  65608. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65609. if (this._textures.length > 0) {
  65610. for (var i = 0; i < this._textures.length; i++) {
  65611. this._engine._releaseTexture(this._textures.data[i]);
  65612. }
  65613. this._textures.reset();
  65614. }
  65615. this.width = desiredWidth;
  65616. this.height = desiredHeight;
  65617. var textureSize = { width: this.width, height: this.height };
  65618. var textureOptions = {
  65619. generateMipMaps: false,
  65620. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65621. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65622. samplingMode: this.renderTargetSamplingMode,
  65623. type: this._textureType
  65624. };
  65625. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65626. if (this._reusable) {
  65627. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65628. }
  65629. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65630. this.onSizeChangedObservable.notifyObservers(this);
  65631. }
  65632. this._textures.forEach(function (texture) {
  65633. if (texture.samples !== _this.samples) {
  65634. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65635. }
  65636. });
  65637. }
  65638. var target;
  65639. if (this._shareOutputWithPostProcess) {
  65640. target = this._shareOutputWithPostProcess.inputTexture;
  65641. }
  65642. else if (this._forcedOutputTexture) {
  65643. target = this._forcedOutputTexture;
  65644. this.width = this._forcedOutputTexture.width;
  65645. this.height = this._forcedOutputTexture.height;
  65646. }
  65647. else {
  65648. target = this.inputTexture;
  65649. }
  65650. // Bind the input of this post process to be used as the output of the previous post process.
  65651. if (this.enablePixelPerfectMode) {
  65652. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65653. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65654. }
  65655. else {
  65656. this._scaleRatio.copyFromFloats(1, 1);
  65657. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65658. }
  65659. this.onActivateObservable.notifyObservers(camera);
  65660. // Clear
  65661. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65662. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65663. }
  65664. if (this._reusable) {
  65665. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65666. }
  65667. return target;
  65668. };
  65669. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65670. /**
  65671. * If the post process is supported.
  65672. */
  65673. get: function () {
  65674. return this._effect.isSupported;
  65675. },
  65676. enumerable: true,
  65677. configurable: true
  65678. });
  65679. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65680. /**
  65681. * The aspect ratio of the output texture.
  65682. */
  65683. get: function () {
  65684. if (this._shareOutputWithPostProcess) {
  65685. return this._shareOutputWithPostProcess.aspectRatio;
  65686. }
  65687. if (this._forcedOutputTexture) {
  65688. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65689. }
  65690. return this.width / this.height;
  65691. },
  65692. enumerable: true,
  65693. configurable: true
  65694. });
  65695. /**
  65696. * Get a value indicating if the post-process is ready to be used
  65697. * @returns true if the post-process is ready (shader is compiled)
  65698. */
  65699. PostProcess.prototype.isReady = function () {
  65700. return this._effect && this._effect.isReady();
  65701. };
  65702. /**
  65703. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65704. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65705. */
  65706. PostProcess.prototype.apply = function () {
  65707. // Check
  65708. if (!this._effect || !this._effect.isReady())
  65709. return null;
  65710. // States
  65711. this._engine.enableEffect(this._effect);
  65712. this._engine.setState(false);
  65713. this._engine.setDepthBuffer(false);
  65714. this._engine.setDepthWrite(false);
  65715. // Alpha
  65716. this._engine.setAlphaMode(this.alphaMode);
  65717. if (this.alphaConstants) {
  65718. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65719. }
  65720. // Bind the output texture of the preivous post process as the input to this post process.
  65721. var source;
  65722. if (this._shareOutputWithPostProcess) {
  65723. source = this._shareOutputWithPostProcess.inputTexture;
  65724. }
  65725. else if (this._forcedOutputTexture) {
  65726. source = this._forcedOutputTexture;
  65727. }
  65728. else {
  65729. source = this.inputTexture;
  65730. }
  65731. this._effect._bindTexture("textureSampler", source);
  65732. // Parameters
  65733. this._effect.setVector2("scale", this._scaleRatio);
  65734. this.onApplyObservable.notifyObservers(this._effect);
  65735. return this._effect;
  65736. };
  65737. PostProcess.prototype._disposeTextures = function () {
  65738. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65739. return;
  65740. }
  65741. if (this._textures.length > 0) {
  65742. for (var i = 0; i < this._textures.length; i++) {
  65743. this._engine._releaseTexture(this._textures.data[i]);
  65744. }
  65745. }
  65746. this._textures.dispose();
  65747. };
  65748. /**
  65749. * Disposes the post process.
  65750. * @param camera The camera to dispose the post process on.
  65751. */
  65752. PostProcess.prototype.dispose = function (camera) {
  65753. camera = camera || this._camera;
  65754. this._disposeTextures();
  65755. if (this._scene) {
  65756. var index_1 = this._scene.postProcesses.indexOf(this);
  65757. if (index_1 !== -1) {
  65758. this._scene.postProcesses.splice(index_1, 1);
  65759. }
  65760. }
  65761. else {
  65762. var index_2 = this._engine.postProcesses.indexOf(this);
  65763. if (index_2 !== -1) {
  65764. this._engine.postProcesses.splice(index_2, 1);
  65765. }
  65766. }
  65767. if (!camera) {
  65768. return;
  65769. }
  65770. camera.detachPostProcess(this);
  65771. var index = camera._postProcesses.indexOf(this);
  65772. if (index === 0 && camera._postProcesses.length > 0) {
  65773. var firstPostProcess = this._camera._getFirstPostProcess();
  65774. if (firstPostProcess) {
  65775. firstPostProcess.markTextureDirty();
  65776. }
  65777. }
  65778. this.onActivateObservable.clear();
  65779. this.onAfterRenderObservable.clear();
  65780. this.onApplyObservable.clear();
  65781. this.onBeforeRenderObservable.clear();
  65782. this.onSizeChangedObservable.clear();
  65783. };
  65784. return PostProcess;
  65785. }());
  65786. BABYLON.PostProcess = PostProcess;
  65787. })(BABYLON || (BABYLON = {}));
  65788. //# sourceMappingURL=babylon.postProcess.js.map
  65789. var BABYLON;
  65790. (function (BABYLON) {
  65791. var PassPostProcess = /** @class */ (function (_super) {
  65792. __extends(PassPostProcess, _super);
  65793. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65794. if (camera === void 0) { camera = null; }
  65795. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65796. if (blockCompilation === void 0) { blockCompilation = false; }
  65797. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65798. }
  65799. return PassPostProcess;
  65800. }(BABYLON.PostProcess));
  65801. BABYLON.PassPostProcess = PassPostProcess;
  65802. })(BABYLON || (BABYLON = {}));
  65803. //# sourceMappingURL=babylon.passPostProcess.js.map
  65804. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65805. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65806. s = arguments[i];
  65807. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65808. t[p] = s[p];
  65809. }
  65810. return t;
  65811. };
  65812. var BABYLON;
  65813. (function (BABYLON) {
  65814. /**
  65815. * Default implementation IShadowGenerator.
  65816. * This is the main object responsible of generating shadows in the framework.
  65817. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65818. */
  65819. var ShadowGenerator = /** @class */ (function () {
  65820. /**
  65821. * Creates a ShadowGenerator object.
  65822. * A ShadowGenerator is the required tool to use the shadows.
  65823. * Each light casting shadows needs to use its own ShadowGenerator.
  65824. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65825. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65826. * @param light The light object generating the shadows.
  65827. * @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.
  65828. */
  65829. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65830. this._bias = 0.00005;
  65831. this._normalBias = 0;
  65832. this._blurBoxOffset = 1;
  65833. this._blurScale = 2;
  65834. this._blurKernel = 1;
  65835. this._useKernelBlur = false;
  65836. this._filter = ShadowGenerator.FILTER_NONE;
  65837. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65838. this._contactHardeningLightSizeUVRatio = 0.1;
  65839. this._darkness = 0;
  65840. this._transparencyShadow = false;
  65841. /**
  65842. * Controls the extent to which the shadows fade out at the edge of the frustum
  65843. * Used only by directionals and spots
  65844. */
  65845. this.frustumEdgeFalloff = 0;
  65846. /**
  65847. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65848. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65849. * It might on the other hand introduce peter panning.
  65850. */
  65851. this.forceBackFacesOnly = false;
  65852. this._lightDirection = BABYLON.Vector3.Zero();
  65853. this._viewMatrix = BABYLON.Matrix.Zero();
  65854. this._projectionMatrix = BABYLON.Matrix.Zero();
  65855. this._transformMatrix = BABYLON.Matrix.Zero();
  65856. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65857. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65858. this._currentFaceIndex = 0;
  65859. this._currentFaceIndexCache = 0;
  65860. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65861. this._mapSize = mapSize;
  65862. this._light = light;
  65863. this._scene = light.getScene();
  65864. light._shadowGenerator = this;
  65865. // Texture type fallback from float to int if not supported.
  65866. var caps = this._scene.getEngine().getCaps();
  65867. if (!useFullFloatFirst) {
  65868. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65869. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65870. }
  65871. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65872. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65873. }
  65874. else {
  65875. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65876. }
  65877. }
  65878. else {
  65879. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65880. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65881. }
  65882. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65883. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65884. }
  65885. else {
  65886. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65887. }
  65888. }
  65889. this._initializeGenerator();
  65890. this._applyFilterValues();
  65891. }
  65892. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65893. /**
  65894. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65895. */
  65896. get: function () {
  65897. return this._bias;
  65898. },
  65899. /**
  65900. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65901. */
  65902. set: function (bias) {
  65903. this._bias = bias;
  65904. },
  65905. enumerable: true,
  65906. configurable: true
  65907. });
  65908. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65909. /**
  65910. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65911. */
  65912. get: function () {
  65913. return this._normalBias;
  65914. },
  65915. /**
  65916. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65917. */
  65918. set: function (normalBias) {
  65919. this._normalBias = normalBias;
  65920. },
  65921. enumerable: true,
  65922. configurable: true
  65923. });
  65924. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65925. /**
  65926. * Gets the blur box offset: offset applied during the blur pass.
  65927. * Only usefull if useKernelBlur = false
  65928. */
  65929. get: function () {
  65930. return this._blurBoxOffset;
  65931. },
  65932. /**
  65933. * Sets the blur box offset: offset applied during the blur pass.
  65934. * Only usefull if useKernelBlur = false
  65935. */
  65936. set: function (value) {
  65937. if (this._blurBoxOffset === value) {
  65938. return;
  65939. }
  65940. this._blurBoxOffset = value;
  65941. this._disposeBlurPostProcesses();
  65942. },
  65943. enumerable: true,
  65944. configurable: true
  65945. });
  65946. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65947. /**
  65948. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65949. * 2 means half of the size.
  65950. */
  65951. get: function () {
  65952. return this._blurScale;
  65953. },
  65954. /**
  65955. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65956. * 2 means half of the size.
  65957. */
  65958. set: function (value) {
  65959. if (this._blurScale === value) {
  65960. return;
  65961. }
  65962. this._blurScale = value;
  65963. this._disposeBlurPostProcesses();
  65964. },
  65965. enumerable: true,
  65966. configurable: true
  65967. });
  65968. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65969. /**
  65970. * Gets the blur kernel: kernel size of the blur pass.
  65971. * Only usefull if useKernelBlur = true
  65972. */
  65973. get: function () {
  65974. return this._blurKernel;
  65975. },
  65976. /**
  65977. * Sets the blur kernel: kernel size of the blur pass.
  65978. * Only usefull if useKernelBlur = true
  65979. */
  65980. set: function (value) {
  65981. if (this._blurKernel === value) {
  65982. return;
  65983. }
  65984. this._blurKernel = value;
  65985. this._disposeBlurPostProcesses();
  65986. },
  65987. enumerable: true,
  65988. configurable: true
  65989. });
  65990. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65991. /**
  65992. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65993. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65994. */
  65995. get: function () {
  65996. return this._useKernelBlur;
  65997. },
  65998. /**
  65999. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66000. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66001. */
  66002. set: function (value) {
  66003. if (this._useKernelBlur === value) {
  66004. return;
  66005. }
  66006. this._useKernelBlur = value;
  66007. this._disposeBlurPostProcesses();
  66008. },
  66009. enumerable: true,
  66010. configurable: true
  66011. });
  66012. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66013. /**
  66014. * Gets the depth scale used in ESM mode.
  66015. */
  66016. get: function () {
  66017. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66018. },
  66019. /**
  66020. * Sets the depth scale used in ESM mode.
  66021. * This can override the scale stored on the light.
  66022. */
  66023. set: function (value) {
  66024. this._depthScale = value;
  66025. },
  66026. enumerable: true,
  66027. configurable: true
  66028. });
  66029. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66030. /**
  66031. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66032. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66033. */
  66034. get: function () {
  66035. return this._filter;
  66036. },
  66037. /**
  66038. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66039. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66040. */
  66041. set: function (value) {
  66042. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66043. if (this._light.needCube()) {
  66044. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66045. this.useExponentialShadowMap = true;
  66046. return;
  66047. }
  66048. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66049. this.useCloseExponentialShadowMap = true;
  66050. return;
  66051. }
  66052. // PCF on cubemap would also be expensive
  66053. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66054. this.usePoissonSampling = true;
  66055. return;
  66056. }
  66057. }
  66058. // Weblg1 fallback for PCF.
  66059. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66060. if (this._scene.getEngine().webGLVersion === 1) {
  66061. this.usePoissonSampling = true;
  66062. return;
  66063. }
  66064. }
  66065. if (this._filter === value) {
  66066. return;
  66067. }
  66068. this._filter = value;
  66069. this._disposeBlurPostProcesses();
  66070. this._applyFilterValues();
  66071. this._light._markMeshesAsLightDirty();
  66072. },
  66073. enumerable: true,
  66074. configurable: true
  66075. });
  66076. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66077. /**
  66078. * Gets if the current filter is set to Poisson Sampling.
  66079. */
  66080. get: function () {
  66081. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66082. },
  66083. /**
  66084. * Sets the current filter to Poisson Sampling.
  66085. */
  66086. set: function (value) {
  66087. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66088. return;
  66089. }
  66090. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66091. },
  66092. enumerable: true,
  66093. configurable: true
  66094. });
  66095. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66096. /**
  66097. * Gets if the current filter is set to VSM.
  66098. * DEPRECATED. Should use useExponentialShadowMap instead.
  66099. */
  66100. get: function () {
  66101. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66102. return this.useExponentialShadowMap;
  66103. },
  66104. /**
  66105. * Sets the current filter is to VSM.
  66106. * DEPRECATED. Should use useExponentialShadowMap instead.
  66107. */
  66108. set: function (value) {
  66109. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66110. this.useExponentialShadowMap = value;
  66111. },
  66112. enumerable: true,
  66113. configurable: true
  66114. });
  66115. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66116. /**
  66117. * Gets if the current filter is set to blurred VSM.
  66118. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66119. */
  66120. get: function () {
  66121. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66122. return this.useBlurExponentialShadowMap;
  66123. },
  66124. /**
  66125. * Sets the current filter is to blurred VSM.
  66126. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66127. */
  66128. set: function (value) {
  66129. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66130. this.useBlurExponentialShadowMap = value;
  66131. },
  66132. enumerable: true,
  66133. configurable: true
  66134. });
  66135. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66136. /**
  66137. * Gets if the current filter is set to ESM.
  66138. */
  66139. get: function () {
  66140. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66141. },
  66142. /**
  66143. * Sets the current filter is to ESM.
  66144. */
  66145. set: function (value) {
  66146. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66147. return;
  66148. }
  66149. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66150. },
  66151. enumerable: true,
  66152. configurable: true
  66153. });
  66154. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66155. /**
  66156. * Gets if the current filter is set to filtered ESM.
  66157. */
  66158. get: function () {
  66159. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66160. },
  66161. /**
  66162. * Gets if the current filter is set to filtered ESM.
  66163. */
  66164. set: function (value) {
  66165. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66166. return;
  66167. }
  66168. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66169. },
  66170. enumerable: true,
  66171. configurable: true
  66172. });
  66173. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66174. /**
  66175. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66176. * exponential to prevent steep falloff artifacts).
  66177. */
  66178. get: function () {
  66179. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66180. },
  66181. /**
  66182. * Sets the current filter to "close ESM" (using the inverse of the
  66183. * exponential to prevent steep falloff artifacts).
  66184. */
  66185. set: function (value) {
  66186. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66187. return;
  66188. }
  66189. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66190. },
  66191. enumerable: true,
  66192. configurable: true
  66193. });
  66194. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66195. /**
  66196. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66197. * exponential to prevent steep falloff artifacts).
  66198. */
  66199. get: function () {
  66200. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66201. },
  66202. /**
  66203. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66204. * exponential to prevent steep falloff artifacts).
  66205. */
  66206. set: function (value) {
  66207. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66208. return;
  66209. }
  66210. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66211. },
  66212. enumerable: true,
  66213. configurable: true
  66214. });
  66215. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66216. /**
  66217. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66218. */
  66219. get: function () {
  66220. return this.filter === ShadowGenerator.FILTER_PCF;
  66221. },
  66222. /**
  66223. * Sets the current filter to "PCF" (percentage closer filtering).
  66224. */
  66225. set: function (value) {
  66226. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66227. return;
  66228. }
  66229. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66230. },
  66231. enumerable: true,
  66232. configurable: true
  66233. });
  66234. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66235. /**
  66236. * Gets the PCF or PCSS Quality.
  66237. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66238. */
  66239. get: function () {
  66240. return this._filteringQuality;
  66241. },
  66242. /**
  66243. * Sets the PCF or PCSS Quality.
  66244. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66245. */
  66246. set: function (filteringQuality) {
  66247. this._filteringQuality = filteringQuality;
  66248. },
  66249. enumerable: true,
  66250. configurable: true
  66251. });
  66252. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66253. /**
  66254. * Gets if the current filter is set to "PCSS" (contact hardening).
  66255. */
  66256. get: function () {
  66257. return this.filter === ShadowGenerator.FILTER_PCSS;
  66258. },
  66259. /**
  66260. * Sets the current filter to "PCSS" (contact hardening).
  66261. */
  66262. set: function (value) {
  66263. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66264. return;
  66265. }
  66266. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66267. },
  66268. enumerable: true,
  66269. configurable: true
  66270. });
  66271. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66272. /**
  66273. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66274. * Using a ratio helps keeping shape stability independently of the map size.
  66275. *
  66276. * It does not account for the light projection as it was having too much
  66277. * instability during the light setup or during light position changes.
  66278. *
  66279. * Only valid if useContactHardeningShadow is true.
  66280. */
  66281. get: function () {
  66282. return this._contactHardeningLightSizeUVRatio;
  66283. },
  66284. /**
  66285. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66286. * Using a ratio helps keeping shape stability independently of the map size.
  66287. *
  66288. * It does not account for the light projection as it was having too much
  66289. * instability during the light setup or during light position changes.
  66290. *
  66291. * Only valid if useContactHardeningShadow is true.
  66292. */
  66293. set: function (contactHardeningLightSizeUVRatio) {
  66294. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66295. },
  66296. enumerable: true,
  66297. configurable: true
  66298. });
  66299. /**
  66300. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66301. * 0 means strongest and 1 would means no shadow.
  66302. * @returns the darkness.
  66303. */
  66304. ShadowGenerator.prototype.getDarkness = function () {
  66305. return this._darkness;
  66306. };
  66307. /**
  66308. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66309. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66310. * @returns the shadow generator allowing fluent coding.
  66311. */
  66312. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66313. if (darkness >= 1.0)
  66314. this._darkness = 1.0;
  66315. else if (darkness <= 0.0)
  66316. this._darkness = 0.0;
  66317. else
  66318. this._darkness = darkness;
  66319. return this;
  66320. };
  66321. /**
  66322. * Sets the ability to have transparent shadow (boolean).
  66323. * @param transparent True if transparent else False
  66324. * @returns the shadow generator allowing fluent coding
  66325. */
  66326. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66327. this._transparencyShadow = transparent;
  66328. return this;
  66329. };
  66330. /**
  66331. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66332. * @returns The render target texture if present otherwise, null
  66333. */
  66334. ShadowGenerator.prototype.getShadowMap = function () {
  66335. return this._shadowMap;
  66336. };
  66337. /**
  66338. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66339. * @returns The render target texture if the shadow map is present otherwise, null
  66340. */
  66341. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66342. if (this._shadowMap2) {
  66343. return this._shadowMap2;
  66344. }
  66345. return this._shadowMap;
  66346. };
  66347. /**
  66348. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66349. * @param mesh Mesh to add
  66350. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66351. * @returns the Shadow Generator itself
  66352. */
  66353. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66354. if (includeDescendants === void 0) { includeDescendants = true; }
  66355. if (!this._shadowMap) {
  66356. return this;
  66357. }
  66358. if (!this._shadowMap.renderList) {
  66359. this._shadowMap.renderList = [];
  66360. }
  66361. this._shadowMap.renderList.push(mesh);
  66362. if (includeDescendants) {
  66363. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66364. }
  66365. return this;
  66366. var _a;
  66367. };
  66368. /**
  66369. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66370. * @param mesh Mesh to remove
  66371. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66372. * @returns the Shadow Generator itself
  66373. */
  66374. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66375. if (includeDescendants === void 0) { includeDescendants = true; }
  66376. if (!this._shadowMap || !this._shadowMap.renderList) {
  66377. return this;
  66378. }
  66379. var index = this._shadowMap.renderList.indexOf(mesh);
  66380. if (index !== -1) {
  66381. this._shadowMap.renderList.splice(index, 1);
  66382. }
  66383. if (includeDescendants) {
  66384. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66385. var child = _a[_i];
  66386. this.removeShadowCaster(child);
  66387. }
  66388. }
  66389. return this;
  66390. };
  66391. /**
  66392. * Returns the associated light object.
  66393. * @returns the light generating the shadow
  66394. */
  66395. ShadowGenerator.prototype.getLight = function () {
  66396. return this._light;
  66397. };
  66398. ShadowGenerator.prototype._initializeGenerator = function () {
  66399. this._light._markMeshesAsLightDirty();
  66400. this._initializeShadowMap();
  66401. };
  66402. ShadowGenerator.prototype._initializeShadowMap = function () {
  66403. var _this = this;
  66404. // Render target
  66405. var engine = this._scene.getEngine();
  66406. if (engine.webGLVersion > 1) {
  66407. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66408. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66409. }
  66410. else {
  66411. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66412. }
  66413. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66414. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66415. this._shadowMap.anisotropicFilteringLevel = 1;
  66416. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66417. this._shadowMap.renderParticles = false;
  66418. this._shadowMap.ignoreCameraViewport = true;
  66419. // Record Face Index before render.
  66420. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66421. _this._currentFaceIndex = faceIndex;
  66422. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66423. engine.setColorWrite(false);
  66424. }
  66425. });
  66426. // Custom render function.
  66427. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66428. // Blur if required afer render.
  66429. this._shadowMap.onAfterUnbindObservable.add(function () {
  66430. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66431. engine.setColorWrite(true);
  66432. }
  66433. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66434. return;
  66435. }
  66436. var shadowMap = _this.getShadowMapForRendering();
  66437. if (shadowMap) {
  66438. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66439. }
  66440. });
  66441. // Clear according to the chosen filter.
  66442. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66443. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66444. this._shadowMap.onClearObservable.add(function (engine) {
  66445. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66446. engine.clear(clearOne, false, true, false);
  66447. }
  66448. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66449. engine.clear(clearZero, true, true, false);
  66450. }
  66451. else {
  66452. engine.clear(clearOne, true, true, false);
  66453. }
  66454. });
  66455. };
  66456. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66457. var _this = this;
  66458. var engine = this._scene.getEngine();
  66459. var targetSize = this._mapSize / this.blurScale;
  66460. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66461. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66462. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66463. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66464. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66465. }
  66466. if (this.useKernelBlur) {
  66467. 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);
  66468. this._kernelBlurXPostprocess.width = targetSize;
  66469. this._kernelBlurXPostprocess.height = targetSize;
  66470. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66471. effect.setTexture("textureSampler", _this._shadowMap);
  66472. });
  66473. 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);
  66474. this._kernelBlurXPostprocess.autoClear = false;
  66475. this._kernelBlurYPostprocess.autoClear = false;
  66476. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66477. this._kernelBlurXPostprocess.packedFloat = true;
  66478. this._kernelBlurYPostprocess.packedFloat = true;
  66479. }
  66480. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66481. }
  66482. else {
  66483. 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);
  66484. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66485. effect.setFloat2("screenSize", targetSize, targetSize);
  66486. effect.setTexture("textureSampler", _this._shadowMap);
  66487. });
  66488. this._boxBlurPostprocess.autoClear = false;
  66489. this._blurPostProcesses = [this._boxBlurPostprocess];
  66490. }
  66491. };
  66492. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66493. var index;
  66494. var engine = this._scene.getEngine();
  66495. if (depthOnlySubMeshes.length) {
  66496. engine.setColorWrite(false);
  66497. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66498. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66499. }
  66500. engine.setColorWrite(true);
  66501. }
  66502. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66503. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66504. }
  66505. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66506. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66507. }
  66508. if (this._transparencyShadow) {
  66509. for (index = 0; index < transparentSubMeshes.length; index++) {
  66510. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66511. }
  66512. }
  66513. };
  66514. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66515. var _this = this;
  66516. var mesh = subMesh.getRenderingMesh();
  66517. var scene = this._scene;
  66518. var engine = scene.getEngine();
  66519. var material = subMesh.getMaterial();
  66520. if (!material) {
  66521. return;
  66522. }
  66523. // Culling
  66524. engine.setState(material.backFaceCulling);
  66525. // Managing instances
  66526. var batch = mesh._getInstancesRenderList(subMesh._id);
  66527. if (batch.mustReturn) {
  66528. return;
  66529. }
  66530. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66531. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66532. engine.enableEffect(this._effect);
  66533. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66534. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66535. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66536. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66537. this._effect.setVector3("lightData", this._cachedDirection);
  66538. }
  66539. else {
  66540. this._effect.setVector3("lightData", this._cachedPosition);
  66541. }
  66542. if (scene.activeCamera) {
  66543. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66544. }
  66545. // Alpha test
  66546. if (material && material.needAlphaTesting()) {
  66547. var alphaTexture = material.getAlphaTestTexture();
  66548. if (alphaTexture) {
  66549. this._effect.setTexture("diffuseSampler", alphaTexture);
  66550. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66551. }
  66552. }
  66553. // Bones
  66554. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66555. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66556. }
  66557. // Morph targets
  66558. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66559. if (this.forceBackFacesOnly) {
  66560. engine.setState(true, 0, false, true);
  66561. }
  66562. // Draw
  66563. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66564. if (this.forceBackFacesOnly) {
  66565. engine.setState(true, 0, false, false);
  66566. }
  66567. }
  66568. else {
  66569. // Need to reset refresh rate of the shadowMap
  66570. if (this._shadowMap) {
  66571. this._shadowMap.resetRefreshCounter();
  66572. }
  66573. }
  66574. };
  66575. ShadowGenerator.prototype._applyFilterValues = function () {
  66576. if (!this._shadowMap) {
  66577. return;
  66578. }
  66579. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66580. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66581. }
  66582. else {
  66583. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66584. }
  66585. };
  66586. /**
  66587. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66588. * @param onCompiled Callback triggered at the and of the effects compilation
  66589. * @param options Sets of optional options forcing the compilation with different modes
  66590. */
  66591. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66592. var _this = this;
  66593. var localOptions = __assign({ useInstances: false }, options);
  66594. var shadowMap = this.getShadowMap();
  66595. if (!shadowMap) {
  66596. if (onCompiled) {
  66597. onCompiled(this);
  66598. }
  66599. return;
  66600. }
  66601. var renderList = shadowMap.renderList;
  66602. if (!renderList) {
  66603. if (onCompiled) {
  66604. onCompiled(this);
  66605. }
  66606. return;
  66607. }
  66608. var subMeshes = new Array();
  66609. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66610. var mesh = renderList_1[_i];
  66611. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66612. }
  66613. if (subMeshes.length === 0) {
  66614. if (onCompiled) {
  66615. onCompiled(this);
  66616. }
  66617. return;
  66618. }
  66619. var currentIndex = 0;
  66620. var checkReady = function () {
  66621. if (!_this._scene || !_this._scene.getEngine()) {
  66622. return;
  66623. }
  66624. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66625. currentIndex++;
  66626. if (currentIndex >= subMeshes.length) {
  66627. if (onCompiled) {
  66628. onCompiled(_this);
  66629. }
  66630. return;
  66631. }
  66632. }
  66633. setTimeout(checkReady, 16);
  66634. };
  66635. checkReady();
  66636. };
  66637. /**
  66638. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66639. * @param options Sets of optional options forcing the compilation with different modes
  66640. * @returns A promise that resolves when the compilation completes
  66641. */
  66642. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66643. var _this = this;
  66644. return new Promise(function (resolve) {
  66645. _this.forceCompilation(function () {
  66646. resolve();
  66647. }, options);
  66648. });
  66649. };
  66650. /**
  66651. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66652. * @param subMesh The submesh we want to render in the shadow map
  66653. * @param useInstances Defines wether will draw in the map using instances
  66654. * @returns true if ready otherwise, false
  66655. */
  66656. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66657. var defines = [];
  66658. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66659. defines.push("#define FLOAT");
  66660. }
  66661. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66662. defines.push("#define ESM");
  66663. }
  66664. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66665. defines.push("#define DEPTHTEXTURE");
  66666. }
  66667. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66668. var mesh = subMesh.getMesh();
  66669. var material = subMesh.getMaterial();
  66670. // Normal bias.
  66671. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66672. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66673. defines.push("#define NORMAL");
  66674. if (mesh.nonUniformScaling) {
  66675. defines.push("#define NONUNIFORMSCALING");
  66676. }
  66677. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66678. defines.push("#define DIRECTIONINLIGHTDATA");
  66679. }
  66680. }
  66681. // Alpha test
  66682. if (material && material.needAlphaTesting()) {
  66683. var alphaTexture = material.getAlphaTestTexture();
  66684. if (alphaTexture) {
  66685. defines.push("#define ALPHATEST");
  66686. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66687. attribs.push(BABYLON.VertexBuffer.UVKind);
  66688. defines.push("#define UV1");
  66689. }
  66690. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66691. if (alphaTexture.coordinatesIndex === 1) {
  66692. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66693. defines.push("#define UV2");
  66694. }
  66695. }
  66696. }
  66697. }
  66698. // Bones
  66699. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66700. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66701. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66702. if (mesh.numBoneInfluencers > 4) {
  66703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66705. }
  66706. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66707. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66708. }
  66709. else {
  66710. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66711. }
  66712. // Morph targets
  66713. var manager = mesh.morphTargetManager;
  66714. var morphInfluencers = 0;
  66715. if (manager) {
  66716. if (manager.numInfluencers > 0) {
  66717. defines.push("#define MORPHTARGETS");
  66718. morphInfluencers = manager.numInfluencers;
  66719. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66720. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66721. }
  66722. }
  66723. // Instances
  66724. if (useInstances) {
  66725. defines.push("#define INSTANCES");
  66726. attribs.push("world0");
  66727. attribs.push("world1");
  66728. attribs.push("world2");
  66729. attribs.push("world3");
  66730. }
  66731. // Get correct effect
  66732. var join = defines.join("\n");
  66733. if (this._cachedDefines !== join) {
  66734. this._cachedDefines = join;
  66735. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66736. }
  66737. if (!this._effect.isReady()) {
  66738. return false;
  66739. }
  66740. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66741. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66742. this._initializeBlurRTTAndPostProcesses();
  66743. }
  66744. }
  66745. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66746. return false;
  66747. }
  66748. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66749. return false;
  66750. }
  66751. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66752. return false;
  66753. }
  66754. return true;
  66755. };
  66756. /**
  66757. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66758. * @param defines Defines of the material we want to update
  66759. * @param lightIndex Index of the light in the enabled light list of the material
  66760. */
  66761. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66762. var scene = this._scene;
  66763. var light = this._light;
  66764. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66765. return;
  66766. }
  66767. defines["SHADOW" + lightIndex] = true;
  66768. if (this.useContactHardeningShadow) {
  66769. defines["SHADOWPCSS" + lightIndex] = true;
  66770. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66771. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66772. }
  66773. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66774. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66775. }
  66776. // else default to high.
  66777. }
  66778. if (this.usePercentageCloserFiltering) {
  66779. defines["SHADOWPCF" + lightIndex] = true;
  66780. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66781. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66782. }
  66783. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66784. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66785. }
  66786. // else default to high.
  66787. }
  66788. else if (this.usePoissonSampling) {
  66789. defines["SHADOWPOISSON" + lightIndex] = true;
  66790. }
  66791. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66792. defines["SHADOWESM" + lightIndex] = true;
  66793. }
  66794. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66795. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66796. }
  66797. if (light.needCube()) {
  66798. defines["SHADOWCUBE" + lightIndex] = true;
  66799. }
  66800. };
  66801. /**
  66802. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66803. * defined in the generator but impacting the effect).
  66804. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66805. * @param effect The effect we are binfing the information for
  66806. */
  66807. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66808. var light = this._light;
  66809. var scene = this._scene;
  66810. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66811. return;
  66812. }
  66813. var camera = scene.activeCamera;
  66814. if (!camera) {
  66815. return;
  66816. }
  66817. var shadowMap = this.getShadowMap();
  66818. if (!shadowMap) {
  66819. return;
  66820. }
  66821. if (!light.needCube()) {
  66822. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66823. }
  66824. // Only PCF uses depth stencil texture.
  66825. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66826. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66827. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66828. }
  66829. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66830. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66831. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66832. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66833. }
  66834. else {
  66835. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66836. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66837. }
  66838. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66839. };
  66840. /**
  66841. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66842. * (eq to shadow prjection matrix * light transform matrix)
  66843. * @returns The transform matrix used to create the shadow map
  66844. */
  66845. ShadowGenerator.prototype.getTransformMatrix = function () {
  66846. var scene = this._scene;
  66847. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66848. return this._transformMatrix;
  66849. }
  66850. this._currentRenderID = scene.getRenderId();
  66851. this._currentFaceIndexCache = this._currentFaceIndex;
  66852. var lightPosition = this._light.position;
  66853. if (this._light.computeTransformedInformation()) {
  66854. lightPosition = this._light.transformedPosition;
  66855. }
  66856. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66857. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66858. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66859. }
  66860. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66861. this._cachedPosition.copyFrom(lightPosition);
  66862. this._cachedDirection.copyFrom(this._lightDirection);
  66863. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66864. var shadowMap = this.getShadowMap();
  66865. if (shadowMap) {
  66866. var renderList = shadowMap.renderList;
  66867. if (renderList) {
  66868. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66869. }
  66870. }
  66871. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66872. }
  66873. return this._transformMatrix;
  66874. };
  66875. /**
  66876. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66877. * Cube and 2D textures for instance.
  66878. */
  66879. ShadowGenerator.prototype.recreateShadowMap = function () {
  66880. var shadowMap = this._shadowMap;
  66881. if (!shadowMap) {
  66882. return;
  66883. }
  66884. // Track render list.
  66885. var renderList = shadowMap.renderList;
  66886. // Clean up existing data.
  66887. this._disposeRTTandPostProcesses();
  66888. // Reinitializes.
  66889. this._initializeGenerator();
  66890. // Reaffect the filter to ensure a correct fallback if necessary.
  66891. this.filter = this.filter;
  66892. // Reaffect the filter.
  66893. this._applyFilterValues();
  66894. // Reaffect Render List.
  66895. this._shadowMap.renderList = renderList;
  66896. };
  66897. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66898. if (this._shadowMap2) {
  66899. this._shadowMap2.dispose();
  66900. this._shadowMap2 = null;
  66901. }
  66902. if (this._boxBlurPostprocess) {
  66903. this._boxBlurPostprocess.dispose();
  66904. this._boxBlurPostprocess = null;
  66905. }
  66906. if (this._kernelBlurXPostprocess) {
  66907. this._kernelBlurXPostprocess.dispose();
  66908. this._kernelBlurXPostprocess = null;
  66909. }
  66910. if (this._kernelBlurYPostprocess) {
  66911. this._kernelBlurYPostprocess.dispose();
  66912. this._kernelBlurYPostprocess = null;
  66913. }
  66914. this._blurPostProcesses = [];
  66915. };
  66916. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66917. if (this._shadowMap) {
  66918. this._shadowMap.dispose();
  66919. this._shadowMap = null;
  66920. }
  66921. this._disposeBlurPostProcesses();
  66922. };
  66923. /**
  66924. * Disposes the ShadowGenerator.
  66925. * Returns nothing.
  66926. */
  66927. ShadowGenerator.prototype.dispose = function () {
  66928. this._disposeRTTandPostProcesses();
  66929. if (this._light) {
  66930. this._light._shadowGenerator = null;
  66931. this._light._markMeshesAsLightDirty();
  66932. }
  66933. };
  66934. /**
  66935. * Serializes the shadow generator setup to a json object.
  66936. * @returns The serialized JSON object
  66937. */
  66938. ShadowGenerator.prototype.serialize = function () {
  66939. var serializationObject = {};
  66940. var shadowMap = this.getShadowMap();
  66941. if (!shadowMap) {
  66942. return serializationObject;
  66943. }
  66944. serializationObject.lightId = this._light.id;
  66945. serializationObject.mapSize = shadowMap.getRenderSize();
  66946. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66947. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66948. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66949. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66950. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66951. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66952. serializationObject.depthScale = this.depthScale;
  66953. serializationObject.darkness = this.getDarkness();
  66954. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66955. serializationObject.blurKernel = this.blurKernel;
  66956. serializationObject.blurScale = this.blurScale;
  66957. serializationObject.useKernelBlur = this.useKernelBlur;
  66958. serializationObject.transparencyShadow = this._transparencyShadow;
  66959. serializationObject.bias = this.bias;
  66960. serializationObject.normalBias = this.normalBias;
  66961. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66962. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66963. serializationObject.filteringQuality = this.filteringQuality;
  66964. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66965. serializationObject.renderList = [];
  66966. if (shadowMap.renderList) {
  66967. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66968. var mesh = shadowMap.renderList[meshIndex];
  66969. serializationObject.renderList.push(mesh.id);
  66970. }
  66971. }
  66972. return serializationObject;
  66973. };
  66974. /**
  66975. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66976. * @param parsedShadowGenerator The JSON object to parse
  66977. * @param scene The scene to create the shadow map for
  66978. * @returns The parsed shadow generator
  66979. */
  66980. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66981. //casting to point light, as light is missing the position attr and typescript complains.
  66982. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66983. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66984. var shadowMap = shadowGenerator.getShadowMap();
  66985. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66986. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66987. meshes.forEach(function (mesh) {
  66988. if (!shadowMap) {
  66989. return;
  66990. }
  66991. if (!shadowMap.renderList) {
  66992. shadowMap.renderList = [];
  66993. }
  66994. shadowMap.renderList.push(mesh);
  66995. });
  66996. }
  66997. if (parsedShadowGenerator.usePoissonSampling) {
  66998. shadowGenerator.usePoissonSampling = true;
  66999. }
  67000. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67001. shadowGenerator.useExponentialShadowMap = true;
  67002. }
  67003. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67004. shadowGenerator.useBlurExponentialShadowMap = true;
  67005. }
  67006. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67007. shadowGenerator.useCloseExponentialShadowMap = true;
  67008. }
  67009. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67010. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67011. }
  67012. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67013. shadowGenerator.usePercentageCloserFiltering = true;
  67014. }
  67015. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67016. shadowGenerator.useContactHardeningShadow = true;
  67017. }
  67018. if (parsedShadowGenerator.filteringQuality) {
  67019. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67020. }
  67021. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67022. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67023. }
  67024. // Backward compat
  67025. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67026. shadowGenerator.useExponentialShadowMap = true;
  67027. }
  67028. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67029. shadowGenerator.useBlurExponentialShadowMap = true;
  67030. }
  67031. if (parsedShadowGenerator.depthScale) {
  67032. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67033. }
  67034. if (parsedShadowGenerator.blurScale) {
  67035. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67036. }
  67037. if (parsedShadowGenerator.blurBoxOffset) {
  67038. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67039. }
  67040. if (parsedShadowGenerator.useKernelBlur) {
  67041. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67042. }
  67043. if (parsedShadowGenerator.blurKernel) {
  67044. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67045. }
  67046. if (parsedShadowGenerator.bias !== undefined) {
  67047. shadowGenerator.bias = parsedShadowGenerator.bias;
  67048. }
  67049. if (parsedShadowGenerator.normalBias !== undefined) {
  67050. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67051. }
  67052. if (parsedShadowGenerator.darkness) {
  67053. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67054. }
  67055. if (parsedShadowGenerator.transparencyShadow) {
  67056. shadowGenerator.setTransparencyShadow(true);
  67057. }
  67058. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67059. return shadowGenerator;
  67060. };
  67061. /**
  67062. * Shadow generator mode None: no filtering applied.
  67063. */
  67064. ShadowGenerator.FILTER_NONE = 0;
  67065. /**
  67066. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67067. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67068. */
  67069. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67070. /**
  67071. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67072. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67073. */
  67074. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67075. /**
  67076. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67077. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67078. */
  67079. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67080. /**
  67081. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67082. * edge artifacts on steep falloff.
  67083. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67084. */
  67085. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67086. /**
  67087. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67088. * edge artifacts on steep falloff.
  67089. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67090. */
  67091. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67092. /**
  67093. * Shadow generator mode PCF: Percentage Closer Filtering
  67094. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67095. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67096. */
  67097. ShadowGenerator.FILTER_PCF = 6;
  67098. /**
  67099. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67100. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67101. * Contact Hardening
  67102. */
  67103. ShadowGenerator.FILTER_PCSS = 7;
  67104. /**
  67105. * Reserved for PCF and PCSS
  67106. * Highest Quality.
  67107. *
  67108. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67109. *
  67110. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67111. */
  67112. ShadowGenerator.QUALITY_HIGH = 0;
  67113. /**
  67114. * Reserved for PCF and PCSS
  67115. * Good tradeoff for quality/perf cross devices
  67116. *
  67117. * Execute PCF on a 3*3 kernel.
  67118. *
  67119. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67120. */
  67121. ShadowGenerator.QUALITY_MEDIUM = 1;
  67122. /**
  67123. * Reserved for PCF and PCSS
  67124. * The lowest quality but the fastest.
  67125. *
  67126. * Execute PCF on a 1*1 kernel.
  67127. *
  67128. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67129. */
  67130. ShadowGenerator.QUALITY_LOW = 2;
  67131. return ShadowGenerator;
  67132. }());
  67133. BABYLON.ShadowGenerator = ShadowGenerator;
  67134. })(BABYLON || (BABYLON = {}));
  67135. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67136. var BABYLON;
  67137. (function (BABYLON) {
  67138. var DefaultLoadingScreen = /** @class */ (function () {
  67139. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67140. if (_loadingText === void 0) { _loadingText = ""; }
  67141. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67142. var _this = this;
  67143. this._renderingCanvas = _renderingCanvas;
  67144. this._loadingText = _loadingText;
  67145. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67146. // Resize
  67147. this._resizeLoadingUI = function () {
  67148. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67149. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67150. if (!_this._loadingDiv) {
  67151. return;
  67152. }
  67153. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67154. _this._loadingDiv.style.left = canvasRect.left + "px";
  67155. _this._loadingDiv.style.top = canvasRect.top + "px";
  67156. _this._loadingDiv.style.width = canvasRect.width + "px";
  67157. _this._loadingDiv.style.height = canvasRect.height + "px";
  67158. };
  67159. }
  67160. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67161. if (this._loadingDiv) {
  67162. // Do not add a loading screen if there is already one
  67163. return;
  67164. }
  67165. this._loadingDiv = document.createElement("div");
  67166. this._loadingDiv.id = "babylonjsLoadingDiv";
  67167. this._loadingDiv.style.opacity = "0";
  67168. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67169. this._loadingDiv.style.pointerEvents = "none";
  67170. // Loading text
  67171. this._loadingTextDiv = document.createElement("div");
  67172. this._loadingTextDiv.style.position = "absolute";
  67173. this._loadingTextDiv.style.left = "0";
  67174. this._loadingTextDiv.style.top = "50%";
  67175. this._loadingTextDiv.style.marginTop = "80px";
  67176. this._loadingTextDiv.style.width = "100%";
  67177. this._loadingTextDiv.style.height = "20px";
  67178. this._loadingTextDiv.style.fontFamily = "Arial";
  67179. this._loadingTextDiv.style.fontSize = "14px";
  67180. this._loadingTextDiv.style.color = "white";
  67181. this._loadingTextDiv.style.textAlign = "center";
  67182. this._loadingTextDiv.innerHTML = "Loading";
  67183. this._loadingDiv.appendChild(this._loadingTextDiv);
  67184. //set the predefined text
  67185. this._loadingTextDiv.innerHTML = this._loadingText;
  67186. // Generating keyframes
  67187. var style = document.createElement('style');
  67188. style.type = 'text/css';
  67189. 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 }";
  67190. style.innerHTML = keyFrames;
  67191. document.getElementsByTagName('head')[0].appendChild(style);
  67192. // Loading img
  67193. var imgBack = new Image();
  67194. 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";
  67195. imgBack.style.position = "absolute";
  67196. imgBack.style.left = "50%";
  67197. imgBack.style.top = "50%";
  67198. imgBack.style.marginLeft = "-60px";
  67199. imgBack.style.marginTop = "-60px";
  67200. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67201. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67202. imgBack.style.transformOrigin = "50% 50%";
  67203. imgBack.style.webkitTransformOrigin = "50% 50%";
  67204. this._loadingDiv.appendChild(imgBack);
  67205. this._resizeLoadingUI();
  67206. window.addEventListener("resize", this._resizeLoadingUI);
  67207. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67208. document.body.appendChild(this._loadingDiv);
  67209. this._loadingDiv.style.opacity = "1";
  67210. };
  67211. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67212. var _this = this;
  67213. if (!this._loadingDiv) {
  67214. return;
  67215. }
  67216. var onTransitionEnd = function () {
  67217. if (!_this._loadingDiv) {
  67218. return;
  67219. }
  67220. document.body.removeChild(_this._loadingDiv);
  67221. window.removeEventListener("resize", _this._resizeLoadingUI);
  67222. _this._loadingDiv = null;
  67223. };
  67224. this._loadingDiv.style.opacity = "0";
  67225. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67226. };
  67227. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67228. set: function (text) {
  67229. this._loadingText = text;
  67230. if (this._loadingTextDiv) {
  67231. this._loadingTextDiv.innerHTML = this._loadingText;
  67232. }
  67233. },
  67234. enumerable: true,
  67235. configurable: true
  67236. });
  67237. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67238. get: function () {
  67239. return this._loadingDivBackgroundColor;
  67240. },
  67241. set: function (color) {
  67242. this._loadingDivBackgroundColor = color;
  67243. if (!this._loadingDiv) {
  67244. return;
  67245. }
  67246. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67247. },
  67248. enumerable: true,
  67249. configurable: true
  67250. });
  67251. return DefaultLoadingScreen;
  67252. }());
  67253. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67254. })(BABYLON || (BABYLON = {}));
  67255. //# sourceMappingURL=babylon.loadingScreen.js.map
  67256. var BABYLON;
  67257. (function (BABYLON) {
  67258. var SceneLoaderProgressEvent = /** @class */ (function () {
  67259. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67260. this.lengthComputable = lengthComputable;
  67261. this.loaded = loaded;
  67262. this.total = total;
  67263. }
  67264. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67265. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67266. };
  67267. return SceneLoaderProgressEvent;
  67268. }());
  67269. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67270. var SceneLoader = /** @class */ (function () {
  67271. function SceneLoader() {
  67272. }
  67273. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67274. get: function () {
  67275. return 0;
  67276. },
  67277. enumerable: true,
  67278. configurable: true
  67279. });
  67280. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67281. get: function () {
  67282. return 1;
  67283. },
  67284. enumerable: true,
  67285. configurable: true
  67286. });
  67287. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67288. get: function () {
  67289. return 2;
  67290. },
  67291. enumerable: true,
  67292. configurable: true
  67293. });
  67294. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67295. get: function () {
  67296. return 3;
  67297. },
  67298. enumerable: true,
  67299. configurable: true
  67300. });
  67301. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67302. get: function () {
  67303. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67304. },
  67305. set: function (value) {
  67306. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67307. },
  67308. enumerable: true,
  67309. configurable: true
  67310. });
  67311. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67312. get: function () {
  67313. return SceneLoader._ShowLoadingScreen;
  67314. },
  67315. set: function (value) {
  67316. SceneLoader._ShowLoadingScreen = value;
  67317. },
  67318. enumerable: true,
  67319. configurable: true
  67320. });
  67321. Object.defineProperty(SceneLoader, "loggingLevel", {
  67322. get: function () {
  67323. return SceneLoader._loggingLevel;
  67324. },
  67325. set: function (value) {
  67326. SceneLoader._loggingLevel = value;
  67327. },
  67328. enumerable: true,
  67329. configurable: true
  67330. });
  67331. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67332. get: function () {
  67333. return SceneLoader._CleanBoneMatrixWeights;
  67334. },
  67335. set: function (value) {
  67336. SceneLoader._CleanBoneMatrixWeights = value;
  67337. },
  67338. enumerable: true,
  67339. configurable: true
  67340. });
  67341. SceneLoader._getDefaultPlugin = function () {
  67342. return SceneLoader._registeredPlugins[".babylon"];
  67343. };
  67344. SceneLoader._getPluginForExtension = function (extension) {
  67345. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67346. if (registeredPlugin) {
  67347. return registeredPlugin;
  67348. }
  67349. 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");
  67350. return SceneLoader._getDefaultPlugin();
  67351. };
  67352. SceneLoader._getPluginForDirectLoad = function (data) {
  67353. for (var extension in SceneLoader._registeredPlugins) {
  67354. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67355. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67356. return SceneLoader._registeredPlugins[extension];
  67357. }
  67358. }
  67359. return SceneLoader._getDefaultPlugin();
  67360. };
  67361. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67362. if (sceneFilename.name) {
  67363. sceneFilename = sceneFilename.name;
  67364. }
  67365. var queryStringPosition = sceneFilename.indexOf("?");
  67366. if (queryStringPosition !== -1) {
  67367. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67368. }
  67369. var dotPosition = sceneFilename.lastIndexOf(".");
  67370. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67371. return SceneLoader._getPluginForExtension(extension);
  67372. };
  67373. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67374. SceneLoader._getDirectLoad = function (sceneFilename) {
  67375. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67376. return sceneFilename.substr(5);
  67377. }
  67378. return null;
  67379. };
  67380. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67381. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67382. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67383. var plugin;
  67384. if (registeredPlugin.plugin.createPlugin) {
  67385. plugin = registeredPlugin.plugin.createPlugin();
  67386. }
  67387. else {
  67388. plugin = registeredPlugin.plugin;
  67389. }
  67390. var useArrayBuffer = registeredPlugin.isBinary;
  67391. var database;
  67392. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67393. var dataCallback = function (data, responseURL) {
  67394. if (scene.isDisposed) {
  67395. onError("Scene has been disposed");
  67396. return;
  67397. }
  67398. scene.database = database;
  67399. onSuccess(plugin, data, responseURL);
  67400. };
  67401. var request = null;
  67402. var pluginDisposed = false;
  67403. var onDisposeObservable = plugin.onDisposeObservable;
  67404. if (onDisposeObservable) {
  67405. onDisposeObservable.add(function () {
  67406. pluginDisposed = true;
  67407. if (request) {
  67408. request.abort();
  67409. request = null;
  67410. }
  67411. onDispose();
  67412. });
  67413. }
  67414. var manifestChecked = function () {
  67415. if (pluginDisposed) {
  67416. return;
  67417. }
  67418. var url = rootUrl + sceneFilename;
  67419. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67420. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67421. } : undefined, database, useArrayBuffer, function (request, exception) {
  67422. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67423. });
  67424. };
  67425. if (directLoad) {
  67426. dataCallback(directLoad);
  67427. return plugin;
  67428. }
  67429. if (rootUrl.indexOf("file:") === -1) {
  67430. var engine = scene.getEngine();
  67431. var canUseOfflineSupport = engine.enableOfflineSupport;
  67432. if (canUseOfflineSupport) {
  67433. // Also check for exceptions
  67434. var exceptionFound = false;
  67435. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67436. var regex = _a[_i];
  67437. if (regex.test(rootUrl + sceneFilename)) {
  67438. exceptionFound = true;
  67439. break;
  67440. }
  67441. }
  67442. canUseOfflineSupport = !exceptionFound;
  67443. }
  67444. if (canUseOfflineSupport) {
  67445. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67446. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67447. }
  67448. else {
  67449. manifestChecked();
  67450. }
  67451. }
  67452. // Loading file from disk via input file or drag'n'drop
  67453. else {
  67454. var fileOrString = sceneFilename;
  67455. if (fileOrString.name) { // File
  67456. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67457. }
  67458. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67459. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67460. }
  67461. else {
  67462. onError("Unable to find file named " + sceneFilename);
  67463. }
  67464. }
  67465. return plugin;
  67466. };
  67467. // Public functions
  67468. SceneLoader.GetPluginForExtension = function (extension) {
  67469. return SceneLoader._getPluginForExtension(extension).plugin;
  67470. };
  67471. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67472. return !!SceneLoader._registeredPlugins[extension];
  67473. };
  67474. SceneLoader.RegisterPlugin = function (plugin) {
  67475. if (typeof plugin.extensions === "string") {
  67476. var extension = plugin.extensions;
  67477. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67478. plugin: plugin,
  67479. isBinary: false
  67480. };
  67481. }
  67482. else {
  67483. var extensions = plugin.extensions;
  67484. Object.keys(extensions).forEach(function (extension) {
  67485. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67486. plugin: plugin,
  67487. isBinary: extensions[extension].isBinary
  67488. };
  67489. });
  67490. }
  67491. };
  67492. /**
  67493. * Import meshes into a scene
  67494. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67495. * @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)
  67496. * @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)
  67497. * @param scene the instance of BABYLON.Scene to append to
  67498. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67499. * @param onProgress a callback with a progress event for each file being loaded
  67500. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67501. * @param pluginExtension the extension used to determine the plugin
  67502. * @returns The loaded plugin
  67503. */
  67504. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67505. if (sceneFilename === void 0) { sceneFilename = ""; }
  67506. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67507. if (onSuccess === void 0) { onSuccess = null; }
  67508. if (onProgress === void 0) { onProgress = null; }
  67509. if (onError === void 0) { onError = null; }
  67510. if (pluginExtension === void 0) { pluginExtension = null; }
  67511. if (!scene) {
  67512. BABYLON.Tools.Error("No scene available to import mesh to");
  67513. return null;
  67514. }
  67515. if (!sceneFilename) {
  67516. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67517. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67518. }
  67519. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67520. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67521. return null;
  67522. }
  67523. var loadingToken = {};
  67524. scene._addPendingData(loadingToken);
  67525. var disposeHandler = function () {
  67526. scene._removePendingData(loadingToken);
  67527. };
  67528. var errorHandler = function (message, exception) {
  67529. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67530. if (onError) {
  67531. onError(scene, errorMessage, exception);
  67532. }
  67533. else {
  67534. BABYLON.Tools.Error(errorMessage);
  67535. // should the exception be thrown?
  67536. }
  67537. disposeHandler();
  67538. };
  67539. var progressHandler = onProgress ? function (event) {
  67540. try {
  67541. onProgress(event);
  67542. }
  67543. catch (e) {
  67544. errorHandler("Error in onProgress callback", e);
  67545. }
  67546. } : undefined;
  67547. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67548. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67549. if (onSuccess) {
  67550. try {
  67551. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67552. }
  67553. catch (e) {
  67554. errorHandler("Error in onSuccess callback", e);
  67555. }
  67556. }
  67557. scene._removePendingData(loadingToken);
  67558. };
  67559. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67560. if (plugin.rewriteRootURL) {
  67561. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67562. }
  67563. if (sceneFilename === "") {
  67564. if (sceneFilename === "") {
  67565. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67566. }
  67567. }
  67568. if (plugin.importMesh) {
  67569. var syncedPlugin = plugin;
  67570. var meshes = new Array();
  67571. var particleSystems = new Array();
  67572. var skeletons = new Array();
  67573. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67574. return;
  67575. }
  67576. scene.loadingPluginName = plugin.name;
  67577. successHandler(meshes, particleSystems, skeletons, []);
  67578. }
  67579. else {
  67580. var asyncedPlugin = plugin;
  67581. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67582. scene.loadingPluginName = plugin.name;
  67583. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67584. }).catch(function (error) {
  67585. errorHandler(error.message, error);
  67586. });
  67587. }
  67588. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67589. };
  67590. /**
  67591. * Import meshes into a scene
  67592. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67593. * @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)
  67594. * @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)
  67595. * @param scene the instance of BABYLON.Scene to append to
  67596. * @param onProgress a callback with a progress event for each file being loaded
  67597. * @param pluginExtension the extension used to determine the plugin
  67598. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67599. */
  67600. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67601. if (sceneFilename === void 0) { sceneFilename = ""; }
  67602. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67603. if (onProgress === void 0) { onProgress = null; }
  67604. if (pluginExtension === void 0) { pluginExtension = null; }
  67605. return new Promise(function (resolve, reject) {
  67606. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67607. resolve({
  67608. meshes: meshes,
  67609. particleSystems: particleSystems,
  67610. skeletons: skeletons,
  67611. animationGroups: animationGroups
  67612. });
  67613. }, onProgress, function (scene, message, exception) {
  67614. reject(exception || new Error(message));
  67615. }, pluginExtension);
  67616. });
  67617. };
  67618. /**
  67619. * Load a scene
  67620. * @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)
  67621. * @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)
  67622. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67623. * @param onSuccess a callback with the scene when import succeeds
  67624. * @param onProgress a callback with a progress event for each file being loaded
  67625. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67626. * @param pluginExtension the extension used to determine the plugin
  67627. * @returns The loaded plugin
  67628. */
  67629. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67630. if (onSuccess === void 0) { onSuccess = null; }
  67631. if (onProgress === void 0) { onProgress = null; }
  67632. if (onError === void 0) { onError = null; }
  67633. if (pluginExtension === void 0) { pluginExtension = null; }
  67634. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67635. };
  67636. /**
  67637. * Load a scene
  67638. * @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)
  67639. * @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)
  67640. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67641. * @param onProgress a callback with a progress event for each file being loaded
  67642. * @param pluginExtension the extension used to determine the plugin
  67643. * @returns The loaded scene
  67644. */
  67645. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67646. if (onProgress === void 0) { onProgress = null; }
  67647. if (pluginExtension === void 0) { pluginExtension = null; }
  67648. return new Promise(function (resolve, reject) {
  67649. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67650. resolve(scene);
  67651. }, onProgress, function (scene, message, exception) {
  67652. reject(exception || new Error(message));
  67653. }, pluginExtension);
  67654. });
  67655. };
  67656. /**
  67657. * Append a scene
  67658. * @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)
  67659. * @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)
  67660. * @param scene is the instance of BABYLON.Scene to append to
  67661. * @param onSuccess a callback with the scene when import succeeds
  67662. * @param onProgress a callback with a progress event for each file being loaded
  67663. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67664. * @param pluginExtension the extension used to determine the plugin
  67665. * @returns The loaded plugin
  67666. */
  67667. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67668. if (sceneFilename === void 0) { sceneFilename = ""; }
  67669. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67670. if (onSuccess === void 0) { onSuccess = null; }
  67671. if (onProgress === void 0) { onProgress = null; }
  67672. if (onError === void 0) { onError = null; }
  67673. if (pluginExtension === void 0) { pluginExtension = null; }
  67674. if (!scene) {
  67675. BABYLON.Tools.Error("No scene available to append to");
  67676. return null;
  67677. }
  67678. if (!sceneFilename) {
  67679. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67680. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67681. }
  67682. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67683. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67684. return null;
  67685. }
  67686. if (SceneLoader.ShowLoadingScreen) {
  67687. scene.getEngine().displayLoadingUI();
  67688. }
  67689. var loadingToken = {};
  67690. scene._addPendingData(loadingToken);
  67691. var disposeHandler = function () {
  67692. scene._removePendingData(loadingToken);
  67693. scene.getEngine().hideLoadingUI();
  67694. };
  67695. var errorHandler = function (message, exception) {
  67696. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67697. if (onError) {
  67698. onError(scene, errorMessage, exception);
  67699. }
  67700. else {
  67701. BABYLON.Tools.Error(errorMessage);
  67702. // should the exception be thrown?
  67703. }
  67704. disposeHandler();
  67705. };
  67706. var progressHandler = onProgress ? function (event) {
  67707. try {
  67708. onProgress(event);
  67709. }
  67710. catch (e) {
  67711. errorHandler("Error in onProgress callback", e);
  67712. }
  67713. } : undefined;
  67714. var successHandler = function () {
  67715. if (onSuccess) {
  67716. try {
  67717. onSuccess(scene);
  67718. }
  67719. catch (e) {
  67720. errorHandler("Error in onSuccess callback", e);
  67721. }
  67722. }
  67723. scene._removePendingData(loadingToken);
  67724. };
  67725. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67726. if (sceneFilename === "") {
  67727. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67728. }
  67729. if (plugin.load) {
  67730. var syncedPlugin = plugin;
  67731. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67732. return;
  67733. }
  67734. scene.loadingPluginName = plugin.name;
  67735. successHandler();
  67736. }
  67737. else {
  67738. var asyncedPlugin = plugin;
  67739. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67740. scene.loadingPluginName = plugin.name;
  67741. successHandler();
  67742. }).catch(function (error) {
  67743. errorHandler(error.message, error);
  67744. });
  67745. }
  67746. if (SceneLoader.ShowLoadingScreen) {
  67747. scene.executeWhenReady(function () {
  67748. scene.getEngine().hideLoadingUI();
  67749. });
  67750. }
  67751. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67752. };
  67753. /**
  67754. * Append a scene
  67755. * @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)
  67756. * @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)
  67757. * @param scene is the instance of BABYLON.Scene to append to
  67758. * @param onProgress a callback with a progress event for each file being loaded
  67759. * @param pluginExtension the extension used to determine the plugin
  67760. * @returns The given scene
  67761. */
  67762. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67763. if (sceneFilename === void 0) { sceneFilename = ""; }
  67764. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67765. if (onProgress === void 0) { onProgress = null; }
  67766. if (pluginExtension === void 0) { pluginExtension = null; }
  67767. return new Promise(function (resolve, reject) {
  67768. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67769. resolve(scene);
  67770. }, onProgress, function (scene, message, exception) {
  67771. reject(exception || new Error(message));
  67772. }, pluginExtension);
  67773. });
  67774. };
  67775. /**
  67776. * Load a scene into an asset container
  67777. * @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)
  67778. * @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)
  67779. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67780. * @param onSuccess a callback with the scene when import succeeds
  67781. * @param onProgress a callback with a progress event for each file being loaded
  67782. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67783. * @param pluginExtension the extension used to determine the plugin
  67784. * @returns The loaded plugin
  67785. */
  67786. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67787. if (sceneFilename === void 0) { sceneFilename = ""; }
  67788. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67789. if (onSuccess === void 0) { onSuccess = null; }
  67790. if (onProgress === void 0) { onProgress = null; }
  67791. if (onError === void 0) { onError = null; }
  67792. if (pluginExtension === void 0) { pluginExtension = null; }
  67793. if (!scene) {
  67794. BABYLON.Tools.Error("No scene available to load asset container to");
  67795. return null;
  67796. }
  67797. if (!sceneFilename) {
  67798. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67799. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67800. }
  67801. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67802. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67803. return null;
  67804. }
  67805. var loadingToken = {};
  67806. scene._addPendingData(loadingToken);
  67807. var disposeHandler = function () {
  67808. scene._removePendingData(loadingToken);
  67809. };
  67810. var errorHandler = function (message, exception) {
  67811. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67812. if (onError) {
  67813. onError(scene, errorMessage, exception);
  67814. }
  67815. else {
  67816. BABYLON.Tools.Error(errorMessage);
  67817. // should the exception be thrown?
  67818. }
  67819. disposeHandler();
  67820. };
  67821. var progressHandler = onProgress ? function (event) {
  67822. try {
  67823. onProgress(event);
  67824. }
  67825. catch (e) {
  67826. errorHandler("Error in onProgress callback", e);
  67827. }
  67828. } : undefined;
  67829. var successHandler = function (assets) {
  67830. if (onSuccess) {
  67831. try {
  67832. onSuccess(assets);
  67833. }
  67834. catch (e) {
  67835. errorHandler("Error in onSuccess callback", e);
  67836. }
  67837. }
  67838. scene._removePendingData(loadingToken);
  67839. };
  67840. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67841. if (plugin.loadAssetContainer) {
  67842. var syncedPlugin = plugin;
  67843. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67844. if (!assetContainer) {
  67845. return;
  67846. }
  67847. scene.loadingPluginName = plugin.name;
  67848. successHandler(assetContainer);
  67849. }
  67850. else if (plugin.loadAssetContainerAsync) {
  67851. var asyncedPlugin = plugin;
  67852. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67853. scene.loadingPluginName = plugin.name;
  67854. successHandler(assetContainer);
  67855. }).catch(function (error) {
  67856. errorHandler(error.message, error);
  67857. });
  67858. }
  67859. else {
  67860. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67861. }
  67862. if (SceneLoader.ShowLoadingScreen) {
  67863. scene.executeWhenReady(function () {
  67864. scene.getEngine().hideLoadingUI();
  67865. });
  67866. }
  67867. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67868. };
  67869. /**
  67870. * Load a scene into an asset container
  67871. * @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)
  67872. * @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)
  67873. * @param scene is the instance of BABYLON.Scene to append to
  67874. * @param onProgress a callback with a progress event for each file being loaded
  67875. * @param pluginExtension the extension used to determine the plugin
  67876. * @returns The loaded asset container
  67877. */
  67878. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67879. if (sceneFilename === void 0) { sceneFilename = ""; }
  67880. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67881. if (onProgress === void 0) { onProgress = null; }
  67882. if (pluginExtension === void 0) { pluginExtension = null; }
  67883. return new Promise(function (resolve, reject) {
  67884. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67885. resolve(assetContainer);
  67886. }, onProgress, function (scene, message, exception) {
  67887. reject(exception || new Error(message));
  67888. }, pluginExtension);
  67889. });
  67890. };
  67891. // Flags
  67892. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67893. SceneLoader._ShowLoadingScreen = true;
  67894. SceneLoader._CleanBoneMatrixWeights = false;
  67895. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67896. // Members
  67897. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67898. SceneLoader._registeredPlugins = {};
  67899. return SceneLoader;
  67900. }());
  67901. BABYLON.SceneLoader = SceneLoader;
  67902. ;
  67903. })(BABYLON || (BABYLON = {}));
  67904. //# sourceMappingURL=babylon.sceneLoader.js.map
  67905. var BABYLON;
  67906. (function (BABYLON) {
  67907. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67908. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67909. var parsedMaterial = parsedData.materials[index];
  67910. if (parsedMaterial.id === id) {
  67911. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67912. }
  67913. }
  67914. return null;
  67915. };
  67916. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67917. for (var i in names) {
  67918. if (mesh.name === names[i]) {
  67919. hierarchyIds.push(mesh.id);
  67920. return true;
  67921. }
  67922. }
  67923. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67924. hierarchyIds.push(mesh.id);
  67925. return true;
  67926. }
  67927. return false;
  67928. };
  67929. var logOperation = function (operation, producer) {
  67930. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67931. };
  67932. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67933. if (addToScene === void 0) { addToScene = false; }
  67934. var container = new BABYLON.AssetContainer(scene);
  67935. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67936. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67937. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67938. // and avoid problems with multiple concurrent .babylon loads.
  67939. var log = "importScene has failed JSON parse";
  67940. try {
  67941. var parsedData = JSON.parse(data);
  67942. log = "";
  67943. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67944. var index;
  67945. var cache;
  67946. // Lights
  67947. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67948. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67949. var parsedLight = parsedData.lights[index];
  67950. var light = BABYLON.Light.Parse(parsedLight, scene);
  67951. if (light) {
  67952. container.lights.push(light);
  67953. log += (index === 0 ? "\n\tLights:" : "");
  67954. log += "\n\t\t" + light.toString(fullDetails);
  67955. }
  67956. }
  67957. }
  67958. // Animations
  67959. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67960. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67961. var parsedAnimation = parsedData.animations[index];
  67962. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67963. scene.animations.push(animation);
  67964. container.animations.push(animation);
  67965. log += (index === 0 ? "\n\tAnimations:" : "");
  67966. log += "\n\t\t" + animation.toString(fullDetails);
  67967. }
  67968. }
  67969. // Materials
  67970. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67971. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67972. var parsedMaterial = parsedData.materials[index];
  67973. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67974. container.materials.push(mat);
  67975. log += (index === 0 ? "\n\tMaterials:" : "");
  67976. log += "\n\t\t" + mat.toString(fullDetails);
  67977. }
  67978. }
  67979. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67980. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67981. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67982. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67983. container.multiMaterials.push(mmat);
  67984. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67985. log += "\n\t\t" + mmat.toString(fullDetails);
  67986. }
  67987. }
  67988. // Morph targets
  67989. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67990. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67991. var managerData = _a[_i];
  67992. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67993. }
  67994. }
  67995. // Skeletons
  67996. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67997. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67998. var parsedSkeleton = parsedData.skeletons[index];
  67999. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68000. container.skeletons.push(skeleton);
  68001. log += (index === 0 ? "\n\tSkeletons:" : "");
  68002. log += "\n\t\t" + skeleton.toString(fullDetails);
  68003. }
  68004. }
  68005. // Geometries
  68006. var geometries = parsedData.geometries;
  68007. if (geometries !== undefined && geometries !== null) {
  68008. var addedGeometry = new Array();
  68009. // Boxes
  68010. var boxes = geometries.boxes;
  68011. if (boxes !== undefined && boxes !== null) {
  68012. for (index = 0, cache = boxes.length; index < cache; index++) {
  68013. var parsedBox = boxes[index];
  68014. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68015. }
  68016. }
  68017. // Spheres
  68018. var spheres = geometries.spheres;
  68019. if (spheres !== undefined && spheres !== null) {
  68020. for (index = 0, cache = spheres.length; index < cache; index++) {
  68021. var parsedSphere = spheres[index];
  68022. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68023. }
  68024. }
  68025. // Cylinders
  68026. var cylinders = geometries.cylinders;
  68027. if (cylinders !== undefined && cylinders !== null) {
  68028. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68029. var parsedCylinder = cylinders[index];
  68030. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68031. }
  68032. }
  68033. // Toruses
  68034. var toruses = geometries.toruses;
  68035. if (toruses !== undefined && toruses !== null) {
  68036. for (index = 0, cache = toruses.length; index < cache; index++) {
  68037. var parsedTorus = toruses[index];
  68038. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68039. }
  68040. }
  68041. // Grounds
  68042. var grounds = geometries.grounds;
  68043. if (grounds !== undefined && grounds !== null) {
  68044. for (index = 0, cache = grounds.length; index < cache; index++) {
  68045. var parsedGround = grounds[index];
  68046. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68047. }
  68048. }
  68049. // Planes
  68050. var planes = geometries.planes;
  68051. if (planes !== undefined && planes !== null) {
  68052. for (index = 0, cache = planes.length; index < cache; index++) {
  68053. var parsedPlane = planes[index];
  68054. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68055. }
  68056. }
  68057. // TorusKnots
  68058. var torusKnots = geometries.torusKnots;
  68059. if (torusKnots !== undefined && torusKnots !== null) {
  68060. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68061. var parsedTorusKnot = torusKnots[index];
  68062. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68063. }
  68064. }
  68065. // VertexData
  68066. var vertexData = geometries.vertexData;
  68067. if (vertexData !== undefined && vertexData !== null) {
  68068. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68069. var parsedVertexData = vertexData[index];
  68070. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68071. }
  68072. }
  68073. addedGeometry.forEach(function (g) {
  68074. if (g) {
  68075. container.geometries.push(g);
  68076. }
  68077. });
  68078. }
  68079. // Transform nodes
  68080. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68081. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68082. var parsedTransformNode = parsedData.transformNodes[index];
  68083. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68084. container.transformNodes.push(node);
  68085. }
  68086. }
  68087. // Meshes
  68088. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68089. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68090. var parsedMesh = parsedData.meshes[index];
  68091. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68092. container.meshes.push(mesh);
  68093. log += (index === 0 ? "\n\tMeshes:" : "");
  68094. log += "\n\t\t" + mesh.toString(fullDetails);
  68095. }
  68096. }
  68097. // Cameras
  68098. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68099. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68100. var parsedCamera = parsedData.cameras[index];
  68101. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68102. container.cameras.push(camera);
  68103. log += (index === 0 ? "\n\tCameras:" : "");
  68104. log += "\n\t\t" + camera.toString(fullDetails);
  68105. }
  68106. }
  68107. // Browsing all the graph to connect the dots
  68108. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68109. var camera = scene.cameras[index];
  68110. if (camera._waitingParentId) {
  68111. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68112. camera._waitingParentId = null;
  68113. }
  68114. }
  68115. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68116. var light_1 = scene.lights[index];
  68117. if (light_1 && light_1._waitingParentId) {
  68118. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68119. light_1._waitingParentId = null;
  68120. }
  68121. }
  68122. // Sounds
  68123. // TODO: add sound
  68124. var loadedSounds = [];
  68125. var loadedSound;
  68126. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68127. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68128. var parsedSound = parsedData.sounds[index];
  68129. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68130. if (!parsedSound.url)
  68131. parsedSound.url = parsedSound.name;
  68132. if (!loadedSounds[parsedSound.url]) {
  68133. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68134. loadedSounds[parsedSound.url] = loadedSound;
  68135. container.sounds.push(loadedSound);
  68136. }
  68137. else {
  68138. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68139. }
  68140. }
  68141. else {
  68142. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68143. }
  68144. }
  68145. }
  68146. loadedSounds = [];
  68147. // Connect parents & children and parse actions
  68148. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68149. var transformNode = scene.transformNodes[index];
  68150. if (transformNode._waitingParentId) {
  68151. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68152. transformNode._waitingParentId = null;
  68153. }
  68154. }
  68155. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68156. var mesh = scene.meshes[index];
  68157. if (mesh._waitingParentId) {
  68158. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68159. mesh._waitingParentId = null;
  68160. }
  68161. if (mesh._waitingActions) {
  68162. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68163. mesh._waitingActions = null;
  68164. }
  68165. }
  68166. // freeze world matrix application
  68167. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68168. var currentMesh = scene.meshes[index];
  68169. if (currentMesh._waitingFreezeWorldMatrix) {
  68170. currentMesh.freezeWorldMatrix();
  68171. currentMesh._waitingFreezeWorldMatrix = null;
  68172. }
  68173. else {
  68174. currentMesh.computeWorldMatrix(true);
  68175. }
  68176. }
  68177. // Particles Systems
  68178. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68179. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68180. var parsedParticleSystem = parsedData.particleSystems[index];
  68181. if (parsedParticleSystem.activeParticleCount) {
  68182. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68183. container.particleSystems.push(ps);
  68184. }
  68185. else {
  68186. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68187. container.particleSystems.push(ps);
  68188. }
  68189. }
  68190. }
  68191. // Lens flares
  68192. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68193. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68194. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68195. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68196. container.lensFlareSystems.push(lf);
  68197. }
  68198. }
  68199. // Shadows
  68200. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68201. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68202. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68203. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68204. container.shadowGenerators.push(sg);
  68205. }
  68206. }
  68207. // Lights exclusions / inclusions
  68208. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68209. var light_2 = scene.lights[index];
  68210. // Excluded check
  68211. if (light_2._excludedMeshesIds.length > 0) {
  68212. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68213. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68214. if (excludedMesh) {
  68215. light_2.excludedMeshes.push(excludedMesh);
  68216. }
  68217. }
  68218. light_2._excludedMeshesIds = [];
  68219. }
  68220. // Included check
  68221. if (light_2._includedOnlyMeshesIds.length > 0) {
  68222. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68223. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68224. if (includedOnlyMesh) {
  68225. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68226. }
  68227. }
  68228. light_2._includedOnlyMeshesIds = [];
  68229. }
  68230. }
  68231. // Effect layers
  68232. if (parsedData.effectLayers) {
  68233. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68234. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68235. container.effectLayers.push(effectLayer);
  68236. }
  68237. }
  68238. // Actions (scene)
  68239. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68240. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68241. }
  68242. if (!addToScene) {
  68243. container.removeAllFromScene();
  68244. }
  68245. }
  68246. catch (err) {
  68247. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68248. if (onError) {
  68249. onError(msg, err);
  68250. }
  68251. else {
  68252. BABYLON.Tools.Log(msg);
  68253. throw err;
  68254. }
  68255. }
  68256. finally {
  68257. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68258. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68259. }
  68260. }
  68261. return container;
  68262. };
  68263. BABYLON.SceneLoader.RegisterPlugin({
  68264. name: "babylon.js",
  68265. extensions: ".babylon",
  68266. canDirectLoad: function (data) {
  68267. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68268. return true;
  68269. }
  68270. return false;
  68271. },
  68272. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68273. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68274. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68275. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68276. // and avoid problems with multiple concurrent .babylon loads.
  68277. var log = "importMesh has failed JSON parse";
  68278. try {
  68279. var parsedData = JSON.parse(data);
  68280. log = "";
  68281. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68282. if (!meshesNames) {
  68283. meshesNames = null;
  68284. }
  68285. else if (!Array.isArray(meshesNames)) {
  68286. meshesNames = [meshesNames];
  68287. }
  68288. var hierarchyIds = new Array();
  68289. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68290. var loadedSkeletonsIds = [];
  68291. var loadedMaterialsIds = [];
  68292. var index;
  68293. var cache;
  68294. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68295. var parsedMesh = parsedData.meshes[index];
  68296. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68297. if (meshesNames !== null) {
  68298. // Remove found mesh name from list.
  68299. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68300. }
  68301. //Geometry?
  68302. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68303. //does the file contain geometries?
  68304. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68305. //find the correct geometry and add it to the scene
  68306. var found = false;
  68307. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68308. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68309. return;
  68310. }
  68311. else {
  68312. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68313. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68314. switch (geometryType) {
  68315. case "boxes":
  68316. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68317. break;
  68318. case "spheres":
  68319. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68320. break;
  68321. case "cylinders":
  68322. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68323. break;
  68324. case "toruses":
  68325. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68326. break;
  68327. case "grounds":
  68328. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68329. break;
  68330. case "planes":
  68331. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68332. break;
  68333. case "torusKnots":
  68334. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68335. break;
  68336. case "vertexData":
  68337. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68338. break;
  68339. }
  68340. found = true;
  68341. }
  68342. });
  68343. }
  68344. });
  68345. if (found === false) {
  68346. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68347. }
  68348. }
  68349. }
  68350. // Material ?
  68351. if (parsedMesh.materialId) {
  68352. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68353. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68354. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68355. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68356. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68357. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68358. var subMatId = parsedMultiMaterial.materials[matIndex];
  68359. loadedMaterialsIds.push(subMatId);
  68360. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68361. if (mat) {
  68362. log += "\n\tMaterial " + mat.toString(fullDetails);
  68363. }
  68364. }
  68365. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68366. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68367. if (mmat) {
  68368. materialFound = true;
  68369. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68370. }
  68371. break;
  68372. }
  68373. }
  68374. }
  68375. if (materialFound === false) {
  68376. loadedMaterialsIds.push(parsedMesh.materialId);
  68377. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68378. if (!mat) {
  68379. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68380. }
  68381. else {
  68382. log += "\n\tMaterial " + mat.toString(fullDetails);
  68383. }
  68384. }
  68385. }
  68386. // Skeleton ?
  68387. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68388. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68389. if (skeletonAlreadyLoaded === false) {
  68390. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68391. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68392. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68393. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68394. skeletons.push(skeleton);
  68395. loadedSkeletonsIds.push(parsedSkeleton.id);
  68396. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68397. }
  68398. }
  68399. }
  68400. }
  68401. // Morph targets ?
  68402. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68403. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68404. var managerData = _a[_i];
  68405. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68406. }
  68407. }
  68408. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68409. meshes.push(mesh);
  68410. log += "\n\tMesh " + mesh.toString(fullDetails);
  68411. }
  68412. }
  68413. // Connecting parents
  68414. var currentMesh;
  68415. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68416. currentMesh = scene.meshes[index];
  68417. if (currentMesh._waitingParentId) {
  68418. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68419. currentMesh._waitingParentId = null;
  68420. }
  68421. }
  68422. // freeze and compute world matrix application
  68423. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68424. currentMesh = scene.meshes[index];
  68425. if (currentMesh._waitingFreezeWorldMatrix) {
  68426. currentMesh.freezeWorldMatrix();
  68427. currentMesh._waitingFreezeWorldMatrix = null;
  68428. }
  68429. else {
  68430. currentMesh.computeWorldMatrix(true);
  68431. }
  68432. }
  68433. }
  68434. // Particles
  68435. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68436. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68437. var parsedParticleSystem = parsedData.particleSystems[index];
  68438. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68439. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68440. }
  68441. }
  68442. }
  68443. return true;
  68444. }
  68445. catch (err) {
  68446. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68447. if (onError) {
  68448. onError(msg, err);
  68449. }
  68450. else {
  68451. BABYLON.Tools.Log(msg);
  68452. throw err;
  68453. }
  68454. }
  68455. finally {
  68456. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68457. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68458. }
  68459. }
  68460. return false;
  68461. },
  68462. load: function (scene, data, rootUrl, onError) {
  68463. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68464. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68465. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68466. // and avoid problems with multiple concurrent .babylon loads.
  68467. var log = "importScene has failed JSON parse";
  68468. try {
  68469. var parsedData = JSON.parse(data);
  68470. log = "";
  68471. // Scene
  68472. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68473. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68474. }
  68475. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68476. scene.autoClear = parsedData.autoClear;
  68477. }
  68478. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68479. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68480. }
  68481. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68482. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68483. }
  68484. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68485. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68486. }
  68487. // Fog
  68488. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68489. scene.fogMode = parsedData.fogMode;
  68490. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68491. scene.fogStart = parsedData.fogStart;
  68492. scene.fogEnd = parsedData.fogEnd;
  68493. scene.fogDensity = parsedData.fogDensity;
  68494. log += "\tFog mode for scene: ";
  68495. switch (scene.fogMode) {
  68496. // getters not compiling, so using hardcoded
  68497. case 1:
  68498. log += "exp\n";
  68499. break;
  68500. case 2:
  68501. log += "exp2\n";
  68502. break;
  68503. case 3:
  68504. log += "linear\n";
  68505. break;
  68506. }
  68507. }
  68508. //Physics
  68509. if (parsedData.physicsEnabled) {
  68510. var physicsPlugin;
  68511. if (parsedData.physicsEngine === "cannon") {
  68512. physicsPlugin = new BABYLON.CannonJSPlugin();
  68513. }
  68514. else if (parsedData.physicsEngine === "oimo") {
  68515. physicsPlugin = new BABYLON.OimoJSPlugin();
  68516. }
  68517. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68518. //else - default engine, which is currently oimo
  68519. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68520. scene.enablePhysics(physicsGravity, physicsPlugin);
  68521. }
  68522. // Metadata
  68523. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68524. scene.metadata = parsedData.metadata;
  68525. }
  68526. //collisions, if defined. otherwise, default is true
  68527. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68528. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68529. }
  68530. scene.workerCollisions = !!parsedData.workerCollisions;
  68531. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68532. if (!container) {
  68533. return false;
  68534. }
  68535. if (parsedData.autoAnimate) {
  68536. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68537. }
  68538. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68539. scene.setActiveCameraByID(parsedData.activeCameraID);
  68540. }
  68541. // Environment texture
  68542. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68543. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68544. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68545. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68546. if (parsedData.environmentTextureRotationY) {
  68547. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68548. }
  68549. scene.environmentTexture = hdrTexture;
  68550. }
  68551. else {
  68552. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68553. if (parsedData.environmentTextureRotationY) {
  68554. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68555. }
  68556. scene.environmentTexture = cubeTexture;
  68557. }
  68558. if (parsedData.createDefaultSkybox === true) {
  68559. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68560. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68561. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68562. }
  68563. }
  68564. // Finish
  68565. return true;
  68566. }
  68567. catch (err) {
  68568. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68569. if (onError) {
  68570. onError(msg, err);
  68571. }
  68572. else {
  68573. BABYLON.Tools.Log(msg);
  68574. throw err;
  68575. }
  68576. }
  68577. finally {
  68578. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68579. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68580. }
  68581. }
  68582. return false;
  68583. },
  68584. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68585. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68586. return container;
  68587. }
  68588. });
  68589. })(BABYLON || (BABYLON = {}));
  68590. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68591. var BABYLON;
  68592. (function (BABYLON) {
  68593. var FilesInput = /** @class */ (function () {
  68594. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68595. this.onProcessFileCallback = function () { return true; };
  68596. this._engine = engine;
  68597. this._currentScene = scene;
  68598. this._sceneLoadedCallback = sceneLoadedCallback;
  68599. this._progressCallback = progressCallback;
  68600. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68601. this._textureLoadingCallback = textureLoadingCallback;
  68602. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68603. this._onReloadCallback = onReloadCallback;
  68604. this._errorCallback = errorCallback;
  68605. }
  68606. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68607. var _this = this;
  68608. if (elementToMonitor) {
  68609. this._elementToMonitor = elementToMonitor;
  68610. this._dragEnterHandler = function (e) { _this.drag(e); };
  68611. this._dragOverHandler = function (e) { _this.drag(e); };
  68612. this._dropHandler = function (e) { _this.drop(e); };
  68613. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68614. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68615. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68616. }
  68617. };
  68618. FilesInput.prototype.dispose = function () {
  68619. if (!this._elementToMonitor) {
  68620. return;
  68621. }
  68622. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68623. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68624. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68625. };
  68626. FilesInput.prototype.renderFunction = function () {
  68627. if (this._additionalRenderLoopLogicCallback) {
  68628. this._additionalRenderLoopLogicCallback();
  68629. }
  68630. if (this._currentScene) {
  68631. if (this._textureLoadingCallback) {
  68632. var remaining = this._currentScene.getWaitingItemsCount();
  68633. if (remaining > 0) {
  68634. this._textureLoadingCallback(remaining);
  68635. }
  68636. }
  68637. this._currentScene.render();
  68638. }
  68639. };
  68640. FilesInput.prototype.drag = function (e) {
  68641. e.stopPropagation();
  68642. e.preventDefault();
  68643. };
  68644. FilesInput.prototype.drop = function (eventDrop) {
  68645. eventDrop.stopPropagation();
  68646. eventDrop.preventDefault();
  68647. this.loadFiles(eventDrop);
  68648. };
  68649. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68650. var _this = this;
  68651. var reader = folder.createReader();
  68652. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68653. reader.readEntries(function (entries) {
  68654. remaining.count += entries.length;
  68655. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68656. var entry = entries_1[_i];
  68657. if (entry.isFile) {
  68658. entry.file(function (file) {
  68659. file.correctName = relativePath + file.name;
  68660. files.push(file);
  68661. if (--remaining.count === 0) {
  68662. callback();
  68663. }
  68664. });
  68665. }
  68666. else if (entry.isDirectory) {
  68667. _this._traverseFolder(entry, files, remaining, callback);
  68668. }
  68669. }
  68670. if (--remaining.count) {
  68671. callback();
  68672. }
  68673. });
  68674. };
  68675. FilesInput.prototype._processFiles = function (files) {
  68676. for (var i = 0; i < files.length; i++) {
  68677. var name = files[i].correctName.toLowerCase();
  68678. var extension = name.split('.').pop();
  68679. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68680. continue;
  68681. }
  68682. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68683. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68684. this._sceneFileToLoad = files[i];
  68685. }
  68686. else {
  68687. FilesInput.FilesToLoad[name] = files[i];
  68688. }
  68689. }
  68690. };
  68691. FilesInput.prototype.loadFiles = function (event) {
  68692. var _this = this;
  68693. if (this._startingProcessingFilesCallback)
  68694. this._startingProcessingFilesCallback();
  68695. // Handling data transfer via drag'n'drop
  68696. if (event && event.dataTransfer && event.dataTransfer.files) {
  68697. this._filesToLoad = event.dataTransfer.files;
  68698. }
  68699. // Handling files from input files
  68700. if (event && event.target && event.target.files) {
  68701. this._filesToLoad = event.target.files;
  68702. }
  68703. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68704. var files_1 = new Array();
  68705. var folders = [];
  68706. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68707. for (var i = 0; i < this._filesToLoad.length; i++) {
  68708. var fileToLoad = this._filesToLoad[i];
  68709. var name_1 = fileToLoad.name.toLowerCase();
  68710. var entry = void 0;
  68711. fileToLoad.correctName = name_1;
  68712. if (items) {
  68713. var item = items[i];
  68714. if (item.getAsEntry) {
  68715. entry = item.getAsEntry();
  68716. }
  68717. else if (item.webkitGetAsEntry) {
  68718. entry = item.webkitGetAsEntry();
  68719. }
  68720. }
  68721. if (!entry) {
  68722. files_1.push(fileToLoad);
  68723. }
  68724. else {
  68725. if (entry.isDirectory) {
  68726. folders.push(entry);
  68727. }
  68728. else {
  68729. files_1.push(fileToLoad);
  68730. }
  68731. }
  68732. }
  68733. if (folders.length === 0) {
  68734. this._processFiles(files_1);
  68735. this._processReload();
  68736. }
  68737. else {
  68738. var remaining = { count: folders.length };
  68739. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68740. var folder = folders_1[_i];
  68741. this._traverseFolder(folder, files_1, remaining, function () {
  68742. _this._processFiles(files_1);
  68743. if (remaining.count === 0) {
  68744. _this._processReload();
  68745. }
  68746. });
  68747. }
  68748. }
  68749. }
  68750. };
  68751. FilesInput.prototype._processReload = function () {
  68752. if (this._onReloadCallback) {
  68753. this._onReloadCallback(this._sceneFileToLoad);
  68754. }
  68755. else {
  68756. this.reload();
  68757. }
  68758. };
  68759. FilesInput.prototype.reload = function () {
  68760. var _this = this;
  68761. // If a scene file has been provided
  68762. if (this._sceneFileToLoad) {
  68763. if (this._currentScene) {
  68764. if (BABYLON.Tools.errorsCount > 0) {
  68765. BABYLON.Tools.ClearLogCache();
  68766. }
  68767. this._engine.stopRenderLoop();
  68768. }
  68769. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68770. if (_this._progressCallback) {
  68771. _this._progressCallback(progress);
  68772. }
  68773. }).then(function (scene) {
  68774. if (_this._currentScene) {
  68775. _this._currentScene.dispose();
  68776. }
  68777. _this._currentScene = scene;
  68778. if (_this._sceneLoadedCallback) {
  68779. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68780. }
  68781. // Wait for textures and shaders to be ready
  68782. _this._currentScene.executeWhenReady(function () {
  68783. _this._engine.runRenderLoop(function () {
  68784. _this.renderFunction();
  68785. });
  68786. });
  68787. }).catch(function (error) {
  68788. if (_this._errorCallback) {
  68789. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68790. }
  68791. });
  68792. }
  68793. else {
  68794. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68795. }
  68796. };
  68797. FilesInput.FilesToLoad = {};
  68798. return FilesInput;
  68799. }());
  68800. BABYLON.FilesInput = FilesInput;
  68801. })(BABYLON || (BABYLON = {}));
  68802. //# sourceMappingURL=babylon.filesInput.js.map
  68803. var BABYLON;
  68804. (function (BABYLON) {
  68805. /**
  68806. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68807. * The underlying implementation relies on an associative array to ensure the best performances.
  68808. * The value can be anything including 'null' but except 'undefined'
  68809. */
  68810. var StringDictionary = /** @class */ (function () {
  68811. function StringDictionary() {
  68812. this._count = 0;
  68813. this._data = {};
  68814. }
  68815. /**
  68816. * This will clear this dictionary and copy the content from the 'source' one.
  68817. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68818. * @param source the dictionary to take the content from and copy to this dictionary
  68819. */
  68820. StringDictionary.prototype.copyFrom = function (source) {
  68821. var _this = this;
  68822. this.clear();
  68823. source.forEach(function (t, v) { return _this.add(t, v); });
  68824. };
  68825. /**
  68826. * Get a value based from its key
  68827. * @param key the given key to get the matching value from
  68828. * @return the value if found, otherwise undefined is returned
  68829. */
  68830. StringDictionary.prototype.get = function (key) {
  68831. var val = this._data[key];
  68832. if (val !== undefined) {
  68833. return val;
  68834. }
  68835. return undefined;
  68836. };
  68837. /**
  68838. * Get a value from its key or add it if it doesn't exist.
  68839. * This method will ensure you that a given key/data will be present in the dictionary.
  68840. * @param key the given key to get the matching value from
  68841. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68842. * The factory will only be invoked if there's no data for the given key.
  68843. * @return the value corresponding to the key.
  68844. */
  68845. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68846. var val = this.get(key);
  68847. if (val !== undefined) {
  68848. return val;
  68849. }
  68850. val = factory(key);
  68851. if (val) {
  68852. this.add(key, val);
  68853. }
  68854. return val;
  68855. };
  68856. /**
  68857. * Get a value from its key if present in the dictionary otherwise add it
  68858. * @param key the key to get the value from
  68859. * @param val if there's no such key/value pair in the dictionary add it with this value
  68860. * @return the value corresponding to the key
  68861. */
  68862. StringDictionary.prototype.getOrAdd = function (key, val) {
  68863. var curVal = this.get(key);
  68864. if (curVal !== undefined) {
  68865. return curVal;
  68866. }
  68867. this.add(key, val);
  68868. return val;
  68869. };
  68870. /**
  68871. * Check if there's a given key in the dictionary
  68872. * @param key the key to check for
  68873. * @return true if the key is present, false otherwise
  68874. */
  68875. StringDictionary.prototype.contains = function (key) {
  68876. return this._data[key] !== undefined;
  68877. };
  68878. /**
  68879. * Add a new key and its corresponding value
  68880. * @param key the key to add
  68881. * @param value the value corresponding to the key
  68882. * @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
  68883. */
  68884. StringDictionary.prototype.add = function (key, value) {
  68885. if (this._data[key] !== undefined) {
  68886. return false;
  68887. }
  68888. this._data[key] = value;
  68889. ++this._count;
  68890. return true;
  68891. };
  68892. StringDictionary.prototype.set = function (key, value) {
  68893. if (this._data[key] === undefined) {
  68894. return false;
  68895. }
  68896. this._data[key] = value;
  68897. return true;
  68898. };
  68899. /**
  68900. * Get the element of the given key and remove it from the dictionary
  68901. * @param key
  68902. */
  68903. StringDictionary.prototype.getAndRemove = function (key) {
  68904. var val = this.get(key);
  68905. if (val !== undefined) {
  68906. delete this._data[key];
  68907. --this._count;
  68908. return val;
  68909. }
  68910. return null;
  68911. };
  68912. /**
  68913. * Remove a key/value from the dictionary.
  68914. * @param key the key to remove
  68915. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68916. */
  68917. StringDictionary.prototype.remove = function (key) {
  68918. if (this.contains(key)) {
  68919. delete this._data[key];
  68920. --this._count;
  68921. return true;
  68922. }
  68923. return false;
  68924. };
  68925. /**
  68926. * Clear the whole content of the dictionary
  68927. */
  68928. StringDictionary.prototype.clear = function () {
  68929. this._data = {};
  68930. this._count = 0;
  68931. };
  68932. Object.defineProperty(StringDictionary.prototype, "count", {
  68933. get: function () {
  68934. return this._count;
  68935. },
  68936. enumerable: true,
  68937. configurable: true
  68938. });
  68939. /**
  68940. * Execute a callback on each key/val of the dictionary.
  68941. * Note that you can remove any element in this dictionary in the callback implementation
  68942. * @param callback the callback to execute on a given key/value pair
  68943. */
  68944. StringDictionary.prototype.forEach = function (callback) {
  68945. for (var cur in this._data) {
  68946. var val = this._data[cur];
  68947. callback(cur, val);
  68948. }
  68949. };
  68950. /**
  68951. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68952. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68953. * Note that you can remove any element in this dictionary in the callback implementation
  68954. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68955. */
  68956. StringDictionary.prototype.first = function (callback) {
  68957. for (var cur in this._data) {
  68958. var val = this._data[cur];
  68959. var res = callback(cur, val);
  68960. if (res) {
  68961. return res;
  68962. }
  68963. }
  68964. return null;
  68965. };
  68966. return StringDictionary;
  68967. }());
  68968. BABYLON.StringDictionary = StringDictionary;
  68969. })(BABYLON || (BABYLON = {}));
  68970. //# sourceMappingURL=babylon.stringDictionary.js.map
  68971. var BABYLON;
  68972. (function (BABYLON) {
  68973. var Tags = /** @class */ (function () {
  68974. function Tags() {
  68975. }
  68976. Tags.EnableFor = function (obj) {
  68977. obj._tags = obj._tags || {};
  68978. obj.hasTags = function () {
  68979. return Tags.HasTags(obj);
  68980. };
  68981. obj.addTags = function (tagsString) {
  68982. return Tags.AddTagsTo(obj, tagsString);
  68983. };
  68984. obj.removeTags = function (tagsString) {
  68985. return Tags.RemoveTagsFrom(obj, tagsString);
  68986. };
  68987. obj.matchesTagsQuery = function (tagsQuery) {
  68988. return Tags.MatchesQuery(obj, tagsQuery);
  68989. };
  68990. };
  68991. Tags.DisableFor = function (obj) {
  68992. delete obj._tags;
  68993. delete obj.hasTags;
  68994. delete obj.addTags;
  68995. delete obj.removeTags;
  68996. delete obj.matchesTagsQuery;
  68997. };
  68998. Tags.HasTags = function (obj) {
  68999. if (!obj._tags) {
  69000. return false;
  69001. }
  69002. return !BABYLON.Tools.IsEmpty(obj._tags);
  69003. };
  69004. Tags.GetTags = function (obj, asString) {
  69005. if (asString === void 0) { asString = true; }
  69006. if (!obj._tags) {
  69007. return null;
  69008. }
  69009. if (asString) {
  69010. var tagsArray = [];
  69011. for (var tag in obj._tags) {
  69012. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69013. tagsArray.push(tag);
  69014. }
  69015. }
  69016. return tagsArray.join(" ");
  69017. }
  69018. else {
  69019. return obj._tags;
  69020. }
  69021. };
  69022. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69023. // a tag cannot start with '||', '&&', and '!'
  69024. // it cannot contain whitespaces
  69025. Tags.AddTagsTo = function (obj, tagsString) {
  69026. if (!tagsString) {
  69027. return;
  69028. }
  69029. if (typeof tagsString !== "string") {
  69030. return;
  69031. }
  69032. var tags = tagsString.split(" ");
  69033. tags.forEach(function (tag, index, array) {
  69034. Tags._AddTagTo(obj, tag);
  69035. });
  69036. };
  69037. Tags._AddTagTo = function (obj, tag) {
  69038. tag = tag.trim();
  69039. if (tag === "" || tag === "true" || tag === "false") {
  69040. return;
  69041. }
  69042. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69043. return;
  69044. }
  69045. Tags.EnableFor(obj);
  69046. obj._tags[tag] = true;
  69047. };
  69048. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69049. if (!Tags.HasTags(obj)) {
  69050. return;
  69051. }
  69052. var tags = tagsString.split(" ");
  69053. for (var t in tags) {
  69054. Tags._RemoveTagFrom(obj, tags[t]);
  69055. }
  69056. };
  69057. Tags._RemoveTagFrom = function (obj, tag) {
  69058. delete obj._tags[tag];
  69059. };
  69060. Tags.MatchesQuery = function (obj, tagsQuery) {
  69061. if (tagsQuery === undefined) {
  69062. return true;
  69063. }
  69064. if (tagsQuery === "") {
  69065. return Tags.HasTags(obj);
  69066. }
  69067. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69068. };
  69069. return Tags;
  69070. }());
  69071. BABYLON.Tags = Tags;
  69072. })(BABYLON || (BABYLON = {}));
  69073. //# sourceMappingURL=babylon.tags.js.map
  69074. var BABYLON;
  69075. (function (BABYLON) {
  69076. /**
  69077. * Class used to evalaute queries containing `and` and `or` operators
  69078. */
  69079. var AndOrNotEvaluator = /** @class */ (function () {
  69080. function AndOrNotEvaluator() {
  69081. }
  69082. /**
  69083. * Evaluate a query
  69084. * @param query defines the query to evaluate
  69085. * @param evaluateCallback defines the callback used to filter result
  69086. * @returns true if the query matches
  69087. */
  69088. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69089. if (!query.match(/\([^\(\)]*\)/g)) {
  69090. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69091. }
  69092. else {
  69093. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69094. // remove parenthesis
  69095. r = r.slice(1, r.length - 1);
  69096. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69097. });
  69098. }
  69099. if (query === "true") {
  69100. return true;
  69101. }
  69102. if (query === "false") {
  69103. return false;
  69104. }
  69105. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69106. };
  69107. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69108. evaluateCallback = evaluateCallback || (function (r) {
  69109. return r === "true" ? true : false;
  69110. });
  69111. var result;
  69112. var or = parenthesisContent.split("||");
  69113. for (var i in or) {
  69114. if (or.hasOwnProperty(i)) {
  69115. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69116. var and = ori.split("&&");
  69117. if (and.length > 1) {
  69118. for (var j = 0; j < and.length; ++j) {
  69119. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69120. if (andj !== "true" && andj !== "false") {
  69121. if (andj[0] === "!") {
  69122. result = !evaluateCallback(andj.substring(1));
  69123. }
  69124. else {
  69125. result = evaluateCallback(andj);
  69126. }
  69127. }
  69128. else {
  69129. result = andj === "true" ? true : false;
  69130. }
  69131. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69132. ori = "false";
  69133. break;
  69134. }
  69135. }
  69136. }
  69137. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69138. result = true;
  69139. break;
  69140. }
  69141. // result equals false (or undefined)
  69142. if (ori !== "true" && ori !== "false") {
  69143. if (ori[0] === "!") {
  69144. result = !evaluateCallback(ori.substring(1));
  69145. }
  69146. else {
  69147. result = evaluateCallback(ori);
  69148. }
  69149. }
  69150. else {
  69151. result = ori === "true" ? true : false;
  69152. }
  69153. }
  69154. }
  69155. // the whole parenthesis scope is replaced by 'true' or 'false'
  69156. return result ? "true" : "false";
  69157. };
  69158. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69159. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69160. // remove whitespaces
  69161. r = r.replace(/[\s]/g, function () { return ""; });
  69162. return r.length % 2 ? "!" : "";
  69163. });
  69164. booleanString = booleanString.trim();
  69165. if (booleanString === "!true") {
  69166. booleanString = "false";
  69167. }
  69168. else if (booleanString === "!false") {
  69169. booleanString = "true";
  69170. }
  69171. return booleanString;
  69172. };
  69173. return AndOrNotEvaluator;
  69174. }());
  69175. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69176. })(BABYLON || (BABYLON = {}));
  69177. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69178. var BABYLON;
  69179. (function (BABYLON) {
  69180. /**
  69181. * Class used to enable access to IndexedDB
  69182. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69183. */
  69184. var Database = /** @class */ (function () {
  69185. /**
  69186. * Creates a new Database
  69187. * @param urlToScene defines the url to load the scene
  69188. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69189. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69190. */
  69191. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69192. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69193. var _this = this;
  69194. // Handling various flavors of prefixed version of IndexedDB
  69195. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69196. this.callbackManifestChecked = callbackManifestChecked;
  69197. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69198. this.db = null;
  69199. this._enableSceneOffline = false;
  69200. this._enableTexturesOffline = false;
  69201. this.manifestVersionFound = 0;
  69202. this.mustUpdateRessources = false;
  69203. this.hasReachedQuota = false;
  69204. if (!Database.IDBStorageEnabled) {
  69205. this.callbackManifestChecked(true);
  69206. }
  69207. else {
  69208. if (disableManifestCheck) {
  69209. this._enableSceneOffline = true;
  69210. this._enableTexturesOffline = true;
  69211. this.manifestVersionFound = 1;
  69212. BABYLON.Tools.SetImmediate(function () {
  69213. _this.callbackManifestChecked(true);
  69214. });
  69215. }
  69216. else {
  69217. this._checkManifestFile();
  69218. }
  69219. }
  69220. }
  69221. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69222. /**
  69223. * Gets a boolean indicating if scene must be saved in the database
  69224. */
  69225. get: function () {
  69226. return this._enableSceneOffline;
  69227. },
  69228. enumerable: true,
  69229. configurable: true
  69230. });
  69231. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69232. /**
  69233. * Gets a boolean indicating if textures must be saved in the database
  69234. */
  69235. get: function () {
  69236. return this._enableTexturesOffline;
  69237. },
  69238. enumerable: true,
  69239. configurable: true
  69240. });
  69241. Database.prototype._checkManifestFile = function () {
  69242. var _this = this;
  69243. var noManifestFile = function () {
  69244. _this._enableSceneOffline = false;
  69245. _this._enableTexturesOffline = false;
  69246. _this.callbackManifestChecked(false);
  69247. };
  69248. var timeStampUsed = false;
  69249. var manifestURL = this.currentSceneUrl + ".manifest";
  69250. var xhr = new XMLHttpRequest();
  69251. if (navigator.onLine) {
  69252. // Adding a timestamp to by-pass browsers' cache
  69253. timeStampUsed = true;
  69254. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69255. }
  69256. xhr.open("GET", manifestURL, true);
  69257. xhr.addEventListener("load", function () {
  69258. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69259. try {
  69260. var manifestFile = JSON.parse(xhr.response);
  69261. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69262. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69263. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69264. _this.manifestVersionFound = manifestFile.version;
  69265. }
  69266. if (_this.callbackManifestChecked) {
  69267. _this.callbackManifestChecked(true);
  69268. }
  69269. }
  69270. catch (ex) {
  69271. noManifestFile();
  69272. }
  69273. }
  69274. else {
  69275. noManifestFile();
  69276. }
  69277. }, false);
  69278. xhr.addEventListener("error", function (event) {
  69279. if (timeStampUsed) {
  69280. timeStampUsed = false;
  69281. // Let's retry without the timeStamp
  69282. // It could fail when coupled with HTML5 Offline API
  69283. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69284. xhr.open("GET", retryManifestURL, true);
  69285. xhr.send();
  69286. }
  69287. else {
  69288. noManifestFile();
  69289. }
  69290. }, false);
  69291. try {
  69292. xhr.send();
  69293. }
  69294. catch (ex) {
  69295. BABYLON.Tools.Error("Error on XHR send request.");
  69296. this.callbackManifestChecked(false);
  69297. }
  69298. };
  69299. /**
  69300. * Open the database and make it available
  69301. * @param successCallback defines the callback to call on success
  69302. * @param errorCallback defines the callback to call on error
  69303. */
  69304. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69305. var _this = this;
  69306. var handleError = function () {
  69307. _this.isSupported = false;
  69308. if (errorCallback)
  69309. errorCallback();
  69310. };
  69311. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69312. // Your browser doesn't support IndexedDB
  69313. this.isSupported = false;
  69314. if (errorCallback)
  69315. errorCallback();
  69316. }
  69317. else {
  69318. // If the DB hasn't been opened or created yet
  69319. if (!this.db) {
  69320. this.hasReachedQuota = false;
  69321. this.isSupported = true;
  69322. var request = this.idbFactory.open("babylonjs", 1);
  69323. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69324. request.onerror = function (event) {
  69325. handleError();
  69326. };
  69327. // executes when a version change transaction cannot complete due to other active transactions
  69328. request.onblocked = function (event) {
  69329. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69330. handleError();
  69331. };
  69332. // DB has been opened successfully
  69333. request.onsuccess = function (event) {
  69334. _this.db = request.result;
  69335. successCallback();
  69336. };
  69337. // Initialization of the DB. Creating Scenes & Textures stores
  69338. request.onupgradeneeded = function (event) {
  69339. _this.db = (event.target).result;
  69340. if (_this.db) {
  69341. try {
  69342. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69343. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69344. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69345. }
  69346. catch (ex) {
  69347. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69348. handleError();
  69349. }
  69350. }
  69351. };
  69352. }
  69353. // DB has already been created and opened
  69354. else {
  69355. if (successCallback)
  69356. successCallback();
  69357. }
  69358. }
  69359. };
  69360. /**
  69361. * Loads an image from the database
  69362. * @param url defines the url to load from
  69363. * @param image defines the target DOM image
  69364. */
  69365. Database.prototype.loadImageFromDB = function (url, image) {
  69366. var _this = this;
  69367. var completeURL = Database._ReturnFullUrlLocation(url);
  69368. var saveAndLoadImage = function () {
  69369. if (!_this.hasReachedQuota && _this.db !== null) {
  69370. // the texture is not yet in the DB, let's try to save it
  69371. _this._saveImageIntoDBAsync(completeURL, image);
  69372. }
  69373. // If the texture is not in the DB and we've reached the DB quota limit
  69374. // let's load it directly from the web
  69375. else {
  69376. image.src = url;
  69377. }
  69378. };
  69379. if (!this.mustUpdateRessources) {
  69380. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69381. }
  69382. // First time we're download the images or update requested in the manifest file by a version change
  69383. else {
  69384. saveAndLoadImage();
  69385. }
  69386. };
  69387. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69388. if (this.isSupported && this.db !== null) {
  69389. var texture;
  69390. var transaction = this.db.transaction(["textures"]);
  69391. transaction.onabort = function (event) {
  69392. image.src = url;
  69393. };
  69394. transaction.oncomplete = function (event) {
  69395. var blobTextureURL;
  69396. if (texture) {
  69397. var URL = window.URL || window.webkitURL;
  69398. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69399. image.onerror = function () {
  69400. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69401. image.src = url;
  69402. };
  69403. image.src = blobTextureURL;
  69404. }
  69405. else {
  69406. notInDBCallback();
  69407. }
  69408. };
  69409. var getRequest = transaction.objectStore("textures").get(url);
  69410. getRequest.onsuccess = function (event) {
  69411. texture = (event.target).result;
  69412. };
  69413. getRequest.onerror = function (event) {
  69414. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69415. image.src = url;
  69416. };
  69417. }
  69418. else {
  69419. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69420. image.src = url;
  69421. }
  69422. };
  69423. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69424. var _this = this;
  69425. if (this.isSupported) {
  69426. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69427. var generateBlobUrl = function () {
  69428. var blobTextureURL;
  69429. if (blob) {
  69430. var URL = window.URL || window.webkitURL;
  69431. try {
  69432. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69433. }
  69434. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69435. catch (ex) {
  69436. blobTextureURL = URL.createObjectURL(blob);
  69437. }
  69438. }
  69439. if (blobTextureURL) {
  69440. image.src = blobTextureURL;
  69441. }
  69442. };
  69443. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69444. var xhr = new XMLHttpRequest(), blob;
  69445. xhr.open("GET", url, true);
  69446. xhr.responseType = "blob";
  69447. xhr.addEventListener("load", function () {
  69448. if (xhr.status === 200 && _this.db) {
  69449. // Blob as response (XHR2)
  69450. blob = xhr.response;
  69451. var transaction = _this.db.transaction(["textures"], "readwrite");
  69452. // the transaction could abort because of a QuotaExceededError error
  69453. transaction.onabort = function (event) {
  69454. try {
  69455. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69456. var srcElement = (event.srcElement || event.target);
  69457. var error = srcElement.error;
  69458. if (error && error.name === "QuotaExceededError") {
  69459. _this.hasReachedQuota = true;
  69460. }
  69461. }
  69462. catch (ex) { }
  69463. generateBlobUrl();
  69464. };
  69465. transaction.oncomplete = function (event) {
  69466. generateBlobUrl();
  69467. };
  69468. var newTexture = { textureUrl: url, data: blob };
  69469. try {
  69470. // Put the blob into the dabase
  69471. var addRequest = transaction.objectStore("textures").put(newTexture);
  69472. addRequest.onsuccess = function (event) {
  69473. };
  69474. addRequest.onerror = function (event) {
  69475. generateBlobUrl();
  69476. };
  69477. }
  69478. catch (ex) {
  69479. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69480. if (ex.code === 25) {
  69481. Database.IsUASupportingBlobStorage = false;
  69482. }
  69483. image.src = url;
  69484. }
  69485. }
  69486. else {
  69487. image.src = url;
  69488. }
  69489. }, false);
  69490. xhr.addEventListener("error", function (event) {
  69491. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69492. image.src = url;
  69493. }, false);
  69494. xhr.send();
  69495. }
  69496. else {
  69497. image.src = url;
  69498. }
  69499. }
  69500. else {
  69501. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69502. image.src = url;
  69503. }
  69504. };
  69505. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69506. var _this = this;
  69507. var updateVersion = function () {
  69508. // the version is not yet in the DB or we need to update it
  69509. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69510. };
  69511. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69512. };
  69513. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69514. var _this = this;
  69515. if (this.isSupported && this.db) {
  69516. var version;
  69517. try {
  69518. var transaction = this.db.transaction(["versions"]);
  69519. transaction.oncomplete = function (event) {
  69520. if (version) {
  69521. // If the version in the JSON file is different from the version in DB
  69522. if (_this.manifestVersionFound !== version.data) {
  69523. _this.mustUpdateRessources = true;
  69524. updateInDBCallback();
  69525. }
  69526. else {
  69527. callback(version.data);
  69528. }
  69529. }
  69530. // version was not found in DB
  69531. else {
  69532. _this.mustUpdateRessources = true;
  69533. updateInDBCallback();
  69534. }
  69535. };
  69536. transaction.onabort = function (event) {
  69537. callback(-1);
  69538. };
  69539. var getRequest = transaction.objectStore("versions").get(url);
  69540. getRequest.onsuccess = function (event) {
  69541. version = (event.target).result;
  69542. };
  69543. getRequest.onerror = function (event) {
  69544. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69545. callback(-1);
  69546. };
  69547. }
  69548. catch (ex) {
  69549. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69550. callback(-1);
  69551. }
  69552. }
  69553. else {
  69554. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69555. callback(-1);
  69556. }
  69557. };
  69558. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69559. var _this = this;
  69560. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69561. try {
  69562. // Open a transaction to the database
  69563. var transaction = this.db.transaction(["versions"], "readwrite");
  69564. // the transaction could abort because of a QuotaExceededError error
  69565. transaction.onabort = function (event) {
  69566. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69567. var error = event.srcElement['error'];
  69568. if (error && error.name === "QuotaExceededError") {
  69569. _this.hasReachedQuota = true;
  69570. }
  69571. }
  69572. catch (ex) { }
  69573. callback(-1);
  69574. };
  69575. transaction.oncomplete = function (event) {
  69576. callback(_this.manifestVersionFound);
  69577. };
  69578. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69579. // Put the scene into the database
  69580. var addRequest = transaction.objectStore("versions").put(newVersion);
  69581. addRequest.onsuccess = function (event) {
  69582. };
  69583. addRequest.onerror = function (event) {
  69584. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69585. };
  69586. }
  69587. catch (ex) {
  69588. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69589. callback(-1);
  69590. }
  69591. }
  69592. else {
  69593. callback(-1);
  69594. }
  69595. };
  69596. /**
  69597. * Loads a file from database
  69598. * @param url defines the URL to load from
  69599. * @param sceneLoaded defines a callback to call on success
  69600. * @param progressCallBack defines a callback to call when progress changed
  69601. * @param errorCallback defines a callback to call on error
  69602. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69603. */
  69604. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69605. var _this = this;
  69606. var completeUrl = Database._ReturnFullUrlLocation(url);
  69607. var saveAndLoadFile = function () {
  69608. // the scene is not yet in the DB, let's try to save it
  69609. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69610. };
  69611. this._checkVersionFromDB(completeUrl, function (version) {
  69612. if (version !== -1) {
  69613. if (!_this.mustUpdateRessources) {
  69614. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69615. }
  69616. else {
  69617. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69618. }
  69619. }
  69620. else {
  69621. if (errorCallback) {
  69622. errorCallback();
  69623. }
  69624. }
  69625. });
  69626. };
  69627. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69628. if (this.isSupported && this.db) {
  69629. var targetStore;
  69630. if (url.indexOf(".babylon") !== -1) {
  69631. targetStore = "scenes";
  69632. }
  69633. else {
  69634. targetStore = "textures";
  69635. }
  69636. var file;
  69637. var transaction = this.db.transaction([targetStore]);
  69638. transaction.oncomplete = function (event) {
  69639. if (file) {
  69640. callback(file.data);
  69641. }
  69642. // file was not found in DB
  69643. else {
  69644. notInDBCallback();
  69645. }
  69646. };
  69647. transaction.onabort = function (event) {
  69648. notInDBCallback();
  69649. };
  69650. var getRequest = transaction.objectStore(targetStore).get(url);
  69651. getRequest.onsuccess = function (event) {
  69652. file = (event.target).result;
  69653. };
  69654. getRequest.onerror = function (event) {
  69655. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69656. notInDBCallback();
  69657. };
  69658. }
  69659. else {
  69660. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69661. callback();
  69662. }
  69663. };
  69664. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69665. var _this = this;
  69666. if (this.isSupported) {
  69667. var targetStore;
  69668. if (url.indexOf(".babylon") !== -1) {
  69669. targetStore = "scenes";
  69670. }
  69671. else {
  69672. targetStore = "textures";
  69673. }
  69674. // Create XHR
  69675. var xhr = new XMLHttpRequest();
  69676. var fileData;
  69677. xhr.open("GET", url, true);
  69678. if (useArrayBuffer) {
  69679. xhr.responseType = "arraybuffer";
  69680. }
  69681. if (progressCallback) {
  69682. xhr.onprogress = progressCallback;
  69683. }
  69684. xhr.addEventListener("load", function () {
  69685. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69686. // Blob as response (XHR2)
  69687. //fileData = xhr.responseText;
  69688. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69689. if (!_this.hasReachedQuota && _this.db) {
  69690. // Open a transaction to the database
  69691. var transaction = _this.db.transaction([targetStore], "readwrite");
  69692. // the transaction could abort because of a QuotaExceededError error
  69693. transaction.onabort = function (event) {
  69694. try {
  69695. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69696. var error = event.srcElement['error'];
  69697. if (error && error.name === "QuotaExceededError") {
  69698. _this.hasReachedQuota = true;
  69699. }
  69700. }
  69701. catch (ex) { }
  69702. callback(fileData);
  69703. };
  69704. transaction.oncomplete = function (event) {
  69705. callback(fileData);
  69706. };
  69707. var newFile;
  69708. if (targetStore === "scenes") {
  69709. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69710. }
  69711. else {
  69712. newFile = { textureUrl: url, data: fileData };
  69713. }
  69714. try {
  69715. // Put the scene into the database
  69716. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69717. addRequest.onsuccess = function (event) {
  69718. };
  69719. addRequest.onerror = function (event) {
  69720. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69721. };
  69722. }
  69723. catch (ex) {
  69724. callback(fileData);
  69725. }
  69726. }
  69727. else {
  69728. callback(fileData);
  69729. }
  69730. }
  69731. else {
  69732. callback();
  69733. }
  69734. }, false);
  69735. xhr.addEventListener("error", function (event) {
  69736. BABYLON.Tools.Error("error on XHR request.");
  69737. callback();
  69738. }, false);
  69739. xhr.send();
  69740. }
  69741. else {
  69742. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69743. callback();
  69744. }
  69745. };
  69746. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69747. Database.IsUASupportingBlobStorage = true;
  69748. /** Gets a boolean indicating if Database storate is enabled */
  69749. Database.IDBStorageEnabled = true;
  69750. Database._ParseURL = function (url) {
  69751. var a = document.createElement('a');
  69752. a.href = url;
  69753. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69754. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69755. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69756. return absLocation;
  69757. };
  69758. Database._ReturnFullUrlLocation = function (url) {
  69759. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69760. return (Database._ParseURL(window.location.href) + url);
  69761. }
  69762. else {
  69763. return url;
  69764. }
  69765. };
  69766. return Database;
  69767. }());
  69768. BABYLON.Database = Database;
  69769. })(BABYLON || (BABYLON = {}));
  69770. //# sourceMappingURL=babylon.database.js.map
  69771. var BABYLON;
  69772. (function (BABYLON) {
  69773. var FresnelParameters = /** @class */ (function () {
  69774. function FresnelParameters() {
  69775. this._isEnabled = true;
  69776. this.leftColor = BABYLON.Color3.White();
  69777. this.rightColor = BABYLON.Color3.Black();
  69778. this.bias = 0;
  69779. this.power = 1;
  69780. }
  69781. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69782. get: function () {
  69783. return this._isEnabled;
  69784. },
  69785. set: function (value) {
  69786. if (this._isEnabled === value) {
  69787. return;
  69788. }
  69789. this._isEnabled = value;
  69790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69791. },
  69792. enumerable: true,
  69793. configurable: true
  69794. });
  69795. FresnelParameters.prototype.clone = function () {
  69796. var newFresnelParameters = new FresnelParameters();
  69797. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69798. return newFresnelParameters;
  69799. };
  69800. FresnelParameters.prototype.serialize = function () {
  69801. var serializationObject = {};
  69802. serializationObject.isEnabled = this.isEnabled;
  69803. serializationObject.leftColor = this.leftColor.asArray();
  69804. serializationObject.rightColor = this.rightColor.asArray();
  69805. serializationObject.bias = this.bias;
  69806. serializationObject.power = this.power;
  69807. return serializationObject;
  69808. };
  69809. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69810. var fresnelParameters = new FresnelParameters();
  69811. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69812. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69813. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69814. fresnelParameters.bias = parsedFresnelParameters.bias;
  69815. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69816. return fresnelParameters;
  69817. };
  69818. return FresnelParameters;
  69819. }());
  69820. BABYLON.FresnelParameters = FresnelParameters;
  69821. })(BABYLON || (BABYLON = {}));
  69822. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69823. var BABYLON;
  69824. (function (BABYLON) {
  69825. var MultiMaterial = /** @class */ (function (_super) {
  69826. __extends(MultiMaterial, _super);
  69827. function MultiMaterial(name, scene) {
  69828. var _this = _super.call(this, name, scene, true) || this;
  69829. scene.multiMaterials.push(_this);
  69830. _this.subMaterials = new Array();
  69831. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69832. return _this;
  69833. }
  69834. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69835. get: function () {
  69836. return this._subMaterials;
  69837. },
  69838. set: function (value) {
  69839. this._subMaterials = value;
  69840. this._hookArray(value);
  69841. },
  69842. enumerable: true,
  69843. configurable: true
  69844. });
  69845. MultiMaterial.prototype._hookArray = function (array) {
  69846. var _this = this;
  69847. var oldPush = array.push;
  69848. array.push = function () {
  69849. var items = [];
  69850. for (var _i = 0; _i < arguments.length; _i++) {
  69851. items[_i] = arguments[_i];
  69852. }
  69853. var result = oldPush.apply(array, items);
  69854. _this._markAllSubMeshesAsTexturesDirty();
  69855. return result;
  69856. };
  69857. var oldSplice = array.splice;
  69858. array.splice = function (index, deleteCount) {
  69859. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69860. _this._markAllSubMeshesAsTexturesDirty();
  69861. return deleted;
  69862. };
  69863. };
  69864. // Properties
  69865. MultiMaterial.prototype.getSubMaterial = function (index) {
  69866. if (index < 0 || index >= this.subMaterials.length) {
  69867. return this.getScene().defaultMaterial;
  69868. }
  69869. return this.subMaterials[index];
  69870. };
  69871. MultiMaterial.prototype.getActiveTextures = function () {
  69872. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69873. if (subMaterial) {
  69874. return subMaterial.getActiveTextures();
  69875. }
  69876. else {
  69877. return [];
  69878. }
  69879. }));
  69880. var _a;
  69881. };
  69882. // Methods
  69883. MultiMaterial.prototype.getClassName = function () {
  69884. return "MultiMaterial";
  69885. };
  69886. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69887. for (var index = 0; index < this.subMaterials.length; index++) {
  69888. var subMaterial = this.subMaterials[index];
  69889. if (subMaterial) {
  69890. if (subMaterial.storeEffectOnSubMeshes) {
  69891. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69892. return false;
  69893. }
  69894. continue;
  69895. }
  69896. if (!subMaterial.isReady(mesh)) {
  69897. return false;
  69898. }
  69899. }
  69900. }
  69901. return true;
  69902. };
  69903. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69904. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69905. for (var index = 0; index < this.subMaterials.length; index++) {
  69906. var subMaterial = null;
  69907. var current = this.subMaterials[index];
  69908. if (cloneChildren && current) {
  69909. subMaterial = current.clone(name + "-" + current.name);
  69910. }
  69911. else {
  69912. subMaterial = this.subMaterials[index];
  69913. }
  69914. newMultiMaterial.subMaterials.push(subMaterial);
  69915. }
  69916. return newMultiMaterial;
  69917. };
  69918. MultiMaterial.prototype.serialize = function () {
  69919. var serializationObject = {};
  69920. serializationObject.name = this.name;
  69921. serializationObject.id = this.id;
  69922. if (BABYLON.Tags) {
  69923. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69924. }
  69925. serializationObject.materials = [];
  69926. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69927. var subMat = this.subMaterials[matIndex];
  69928. if (subMat) {
  69929. serializationObject.materials.push(subMat.id);
  69930. }
  69931. else {
  69932. serializationObject.materials.push(null);
  69933. }
  69934. }
  69935. return serializationObject;
  69936. };
  69937. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69938. var scene = this.getScene();
  69939. if (!scene) {
  69940. return;
  69941. }
  69942. var index = scene.multiMaterials.indexOf(this);
  69943. if (index >= 0) {
  69944. scene.multiMaterials.splice(index, 1);
  69945. }
  69946. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69947. };
  69948. return MultiMaterial;
  69949. }(BABYLON.Material));
  69950. BABYLON.MultiMaterial = MultiMaterial;
  69951. })(BABYLON || (BABYLON = {}));
  69952. //# sourceMappingURL=babylon.multiMaterial.js.map
  69953. var BABYLON;
  69954. (function (BABYLON) {
  69955. var FreeCameraTouchInput = /** @class */ (function () {
  69956. function FreeCameraTouchInput() {
  69957. this._offsetX = null;
  69958. this._offsetY = null;
  69959. this._pointerPressed = new Array();
  69960. this.touchAngularSensibility = 200000.0;
  69961. this.touchMoveSensibility = 250.0;
  69962. }
  69963. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69964. var _this = this;
  69965. var previousPosition = null;
  69966. if (this._pointerInput === undefined) {
  69967. this._onLostFocus = function (evt) {
  69968. _this._offsetX = null;
  69969. _this._offsetY = null;
  69970. };
  69971. this._pointerInput = function (p, s) {
  69972. var evt = p.event;
  69973. if (evt.pointerType === "mouse") {
  69974. return;
  69975. }
  69976. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69977. if (!noPreventDefault) {
  69978. evt.preventDefault();
  69979. }
  69980. _this._pointerPressed.push(evt.pointerId);
  69981. if (_this._pointerPressed.length !== 1) {
  69982. return;
  69983. }
  69984. previousPosition = {
  69985. x: evt.clientX,
  69986. y: evt.clientY
  69987. };
  69988. }
  69989. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69990. if (!noPreventDefault) {
  69991. evt.preventDefault();
  69992. }
  69993. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69994. if (index === -1) {
  69995. return;
  69996. }
  69997. _this._pointerPressed.splice(index, 1);
  69998. if (index != 0) {
  69999. return;
  70000. }
  70001. previousPosition = null;
  70002. _this._offsetX = null;
  70003. _this._offsetY = null;
  70004. }
  70005. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70006. if (!noPreventDefault) {
  70007. evt.preventDefault();
  70008. }
  70009. if (!previousPosition) {
  70010. return;
  70011. }
  70012. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70013. if (index != 0) {
  70014. return;
  70015. }
  70016. _this._offsetX = evt.clientX - previousPosition.x;
  70017. _this._offsetY = -(evt.clientY - previousPosition.y);
  70018. }
  70019. };
  70020. }
  70021. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70022. if (this._onLostFocus) {
  70023. element.addEventListener("blur", this._onLostFocus);
  70024. }
  70025. };
  70026. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70027. if (this._pointerInput && element) {
  70028. if (this._observer) {
  70029. this.camera.getScene().onPointerObservable.remove(this._observer);
  70030. this._observer = null;
  70031. }
  70032. if (this._onLostFocus) {
  70033. element.removeEventListener("blur", this._onLostFocus);
  70034. this._onLostFocus = null;
  70035. }
  70036. this._pointerPressed = [];
  70037. this._offsetX = null;
  70038. this._offsetY = null;
  70039. }
  70040. };
  70041. FreeCameraTouchInput.prototype.checkInputs = function () {
  70042. if (this._offsetX && this._offsetY) {
  70043. var camera = this.camera;
  70044. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70045. if (this._pointerPressed.length > 1) {
  70046. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70047. }
  70048. else {
  70049. var speed = camera._computeLocalCameraSpeed();
  70050. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70051. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70052. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70053. }
  70054. }
  70055. };
  70056. FreeCameraTouchInput.prototype.getClassName = function () {
  70057. return "FreeCameraTouchInput";
  70058. };
  70059. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70060. return "touch";
  70061. };
  70062. __decorate([
  70063. BABYLON.serialize()
  70064. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70065. __decorate([
  70066. BABYLON.serialize()
  70067. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70068. return FreeCameraTouchInput;
  70069. }());
  70070. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70071. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70072. })(BABYLON || (BABYLON = {}));
  70073. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70074. var BABYLON;
  70075. (function (BABYLON) {
  70076. // We're mainly based on the logic defined into the FreeCamera code
  70077. var TouchCamera = /** @class */ (function (_super) {
  70078. __extends(TouchCamera, _super);
  70079. //-- end properties for backward compatibility for inputs
  70080. function TouchCamera(name, position, scene) {
  70081. var _this = _super.call(this, name, position, scene) || this;
  70082. _this.inputs.addTouch();
  70083. _this._setupInputs();
  70084. return _this;
  70085. }
  70086. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70087. //-- Begin properties for backward compatibility for inputs
  70088. get: function () {
  70089. var touch = this.inputs.attached["touch"];
  70090. if (touch)
  70091. return touch.touchAngularSensibility;
  70092. return 0;
  70093. },
  70094. set: function (value) {
  70095. var touch = this.inputs.attached["touch"];
  70096. if (touch)
  70097. touch.touchAngularSensibility = value;
  70098. },
  70099. enumerable: true,
  70100. configurable: true
  70101. });
  70102. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70103. get: function () {
  70104. var touch = this.inputs.attached["touch"];
  70105. if (touch)
  70106. return touch.touchMoveSensibility;
  70107. return 0;
  70108. },
  70109. set: function (value) {
  70110. var touch = this.inputs.attached["touch"];
  70111. if (touch)
  70112. touch.touchMoveSensibility = value;
  70113. },
  70114. enumerable: true,
  70115. configurable: true
  70116. });
  70117. TouchCamera.prototype.getClassName = function () {
  70118. return "TouchCamera";
  70119. };
  70120. TouchCamera.prototype._setupInputs = function () {
  70121. var mouse = this.inputs.attached["mouse"];
  70122. if (mouse) {
  70123. mouse.touchEnabled = false;
  70124. }
  70125. };
  70126. return TouchCamera;
  70127. }(BABYLON.FreeCamera));
  70128. BABYLON.TouchCamera = TouchCamera;
  70129. })(BABYLON || (BABYLON = {}));
  70130. //# sourceMappingURL=babylon.touchCamera.js.map
  70131. var BABYLON;
  70132. (function (BABYLON) {
  70133. var ProceduralTexture = /** @class */ (function (_super) {
  70134. __extends(ProceduralTexture, _super);
  70135. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70136. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70137. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70138. if (isCube === void 0) { isCube = false; }
  70139. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70140. _this.isCube = isCube;
  70141. _this.isEnabled = true;
  70142. _this._currentRefreshId = -1;
  70143. _this._refreshRate = 1;
  70144. _this._vertexBuffers = {};
  70145. _this._uniforms = new Array();
  70146. _this._samplers = new Array();
  70147. _this._textures = {};
  70148. _this._floats = {};
  70149. _this._floatsArrays = {};
  70150. _this._colors3 = {};
  70151. _this._colors4 = {};
  70152. _this._vectors2 = {};
  70153. _this._vectors3 = {};
  70154. _this._matrices = {};
  70155. _this._fallbackTextureUsed = false;
  70156. scene.proceduralTextures.push(_this);
  70157. _this._engine = scene.getEngine();
  70158. _this.name = name;
  70159. _this.isRenderTarget = true;
  70160. _this._size = size;
  70161. _this._generateMipMaps = generateMipMaps;
  70162. _this.setFragment(fragment);
  70163. _this._fallbackTexture = fallbackTexture;
  70164. if (isCube) {
  70165. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70166. _this.setFloat("face", 0);
  70167. }
  70168. else {
  70169. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70170. }
  70171. // VBO
  70172. var vertices = [];
  70173. vertices.push(1, 1);
  70174. vertices.push(-1, 1);
  70175. vertices.push(-1, -1);
  70176. vertices.push(1, -1);
  70177. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70178. _this._createIndexBuffer();
  70179. return _this;
  70180. }
  70181. ProceduralTexture.prototype._createIndexBuffer = function () {
  70182. var engine = this._engine;
  70183. // Indices
  70184. var indices = [];
  70185. indices.push(0);
  70186. indices.push(1);
  70187. indices.push(2);
  70188. indices.push(0);
  70189. indices.push(2);
  70190. indices.push(3);
  70191. this._indexBuffer = engine.createIndexBuffer(indices);
  70192. };
  70193. ProceduralTexture.prototype._rebuild = function () {
  70194. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70195. if (vb) {
  70196. vb._rebuild();
  70197. }
  70198. this._createIndexBuffer();
  70199. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70200. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70201. }
  70202. };
  70203. ProceduralTexture.prototype.reset = function () {
  70204. if (this._effect === undefined) {
  70205. return;
  70206. }
  70207. var engine = this._engine;
  70208. engine._releaseEffect(this._effect);
  70209. };
  70210. ProceduralTexture.prototype.isReady = function () {
  70211. var _this = this;
  70212. var engine = this._engine;
  70213. var shaders;
  70214. if (!this._fragment) {
  70215. return false;
  70216. }
  70217. if (this._fallbackTextureUsed) {
  70218. return true;
  70219. }
  70220. if (this._fragment.fragmentElement !== undefined) {
  70221. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70222. }
  70223. else {
  70224. shaders = { vertex: "procedural", fragment: this._fragment };
  70225. }
  70226. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70227. _this.releaseInternalTexture();
  70228. if (_this._fallbackTexture) {
  70229. _this._texture = _this._fallbackTexture._texture;
  70230. if (_this._texture) {
  70231. _this._texture.incrementReferences();
  70232. }
  70233. }
  70234. _this._fallbackTextureUsed = true;
  70235. });
  70236. return this._effect.isReady();
  70237. };
  70238. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70239. this._currentRefreshId = -1;
  70240. };
  70241. ProceduralTexture.prototype.setFragment = function (fragment) {
  70242. this._fragment = fragment;
  70243. };
  70244. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70245. get: function () {
  70246. return this._refreshRate;
  70247. },
  70248. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70249. set: function (value) {
  70250. this._refreshRate = value;
  70251. this.resetRefreshCounter();
  70252. },
  70253. enumerable: true,
  70254. configurable: true
  70255. });
  70256. ProceduralTexture.prototype._shouldRender = function () {
  70257. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70258. return false;
  70259. }
  70260. if (this._fallbackTextureUsed) {
  70261. return false;
  70262. }
  70263. if (this._currentRefreshId === -1) { // At least render once
  70264. this._currentRefreshId = 1;
  70265. return true;
  70266. }
  70267. if (this.refreshRate === this._currentRefreshId) {
  70268. this._currentRefreshId = 1;
  70269. return true;
  70270. }
  70271. this._currentRefreshId++;
  70272. return false;
  70273. };
  70274. ProceduralTexture.prototype.getRenderSize = function () {
  70275. return this._size;
  70276. };
  70277. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70278. if (this._fallbackTextureUsed) {
  70279. return;
  70280. }
  70281. this.releaseInternalTexture();
  70282. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70283. };
  70284. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70285. if (this._uniforms.indexOf(uniformName) === -1) {
  70286. this._uniforms.push(uniformName);
  70287. }
  70288. };
  70289. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70290. if (this._samplers.indexOf(name) === -1) {
  70291. this._samplers.push(name);
  70292. }
  70293. this._textures[name] = texture;
  70294. return this;
  70295. };
  70296. ProceduralTexture.prototype.setFloat = function (name, value) {
  70297. this._checkUniform(name);
  70298. this._floats[name] = value;
  70299. return this;
  70300. };
  70301. ProceduralTexture.prototype.setFloats = function (name, value) {
  70302. this._checkUniform(name);
  70303. this._floatsArrays[name] = value;
  70304. return this;
  70305. };
  70306. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70307. this._checkUniform(name);
  70308. this._colors3[name] = value;
  70309. return this;
  70310. };
  70311. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70312. this._checkUniform(name);
  70313. this._colors4[name] = value;
  70314. return this;
  70315. };
  70316. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70317. this._checkUniform(name);
  70318. this._vectors2[name] = value;
  70319. return this;
  70320. };
  70321. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70322. this._checkUniform(name);
  70323. this._vectors3[name] = value;
  70324. return this;
  70325. };
  70326. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70327. this._checkUniform(name);
  70328. this._matrices[name] = value;
  70329. return this;
  70330. };
  70331. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70332. var scene = this.getScene();
  70333. if (!scene) {
  70334. return;
  70335. }
  70336. var engine = this._engine;
  70337. // Render
  70338. engine.enableEffect(this._effect);
  70339. engine.setState(false);
  70340. // Texture
  70341. for (var name in this._textures) {
  70342. this._effect.setTexture(name, this._textures[name]);
  70343. }
  70344. // Float
  70345. for (name in this._floats) {
  70346. this._effect.setFloat(name, this._floats[name]);
  70347. }
  70348. // Floats
  70349. for (name in this._floatsArrays) {
  70350. this._effect.setArray(name, this._floatsArrays[name]);
  70351. }
  70352. // Color3
  70353. for (name in this._colors3) {
  70354. this._effect.setColor3(name, this._colors3[name]);
  70355. }
  70356. // Color4
  70357. for (name in this._colors4) {
  70358. var color = this._colors4[name];
  70359. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70360. }
  70361. // Vector2
  70362. for (name in this._vectors2) {
  70363. this._effect.setVector2(name, this._vectors2[name]);
  70364. }
  70365. // Vector3
  70366. for (name in this._vectors3) {
  70367. this._effect.setVector3(name, this._vectors3[name]);
  70368. }
  70369. // Matrix
  70370. for (name in this._matrices) {
  70371. this._effect.setMatrix(name, this._matrices[name]);
  70372. }
  70373. if (!this._texture) {
  70374. return;
  70375. }
  70376. if (this.isCube) {
  70377. for (var face = 0; face < 6; face++) {
  70378. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70379. // VBOs
  70380. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70381. this._effect.setFloat("face", face);
  70382. // Clear
  70383. engine.clear(scene.clearColor, true, true, true);
  70384. // Draw order
  70385. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70386. // Mipmaps
  70387. if (face === 5) {
  70388. engine.generateMipMapsForCubemap(this._texture);
  70389. }
  70390. }
  70391. }
  70392. else {
  70393. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70394. // VBOs
  70395. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70396. // Clear
  70397. engine.clear(scene.clearColor, true, true, true);
  70398. // Draw order
  70399. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70400. }
  70401. // Unbind
  70402. engine.unBindFramebuffer(this._texture, this.isCube);
  70403. if (this.onGenerated) {
  70404. this.onGenerated();
  70405. }
  70406. };
  70407. ProceduralTexture.prototype.clone = function () {
  70408. var textureSize = this.getSize();
  70409. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70410. // Base texture
  70411. newTexture.hasAlpha = this.hasAlpha;
  70412. newTexture.level = this.level;
  70413. // RenderTarget Texture
  70414. newTexture.coordinatesMode = this.coordinatesMode;
  70415. return newTexture;
  70416. };
  70417. ProceduralTexture.prototype.dispose = function () {
  70418. var scene = this.getScene();
  70419. if (!scene) {
  70420. return;
  70421. }
  70422. var index = scene.proceduralTextures.indexOf(this);
  70423. if (index >= 0) {
  70424. scene.proceduralTextures.splice(index, 1);
  70425. }
  70426. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70427. if (vertexBuffer) {
  70428. vertexBuffer.dispose();
  70429. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70430. }
  70431. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70432. this._indexBuffer = null;
  70433. }
  70434. _super.prototype.dispose.call(this);
  70435. };
  70436. return ProceduralTexture;
  70437. }(BABYLON.Texture));
  70438. BABYLON.ProceduralTexture = ProceduralTexture;
  70439. })(BABYLON || (BABYLON = {}));
  70440. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70441. var BABYLON;
  70442. (function (BABYLON) {
  70443. var CustomProceduralTexture = /** @class */ (function (_super) {
  70444. __extends(CustomProceduralTexture, _super);
  70445. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70446. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70447. _this._animate = true;
  70448. _this._time = 0;
  70449. _this._texturePath = texturePath;
  70450. //Try to load json
  70451. _this.loadJson(texturePath);
  70452. _this.refreshRate = 1;
  70453. return _this;
  70454. }
  70455. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70456. var _this = this;
  70457. var noConfigFile = function () {
  70458. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70459. try {
  70460. _this.setFragment(_this._texturePath);
  70461. }
  70462. catch (ex) {
  70463. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70464. }
  70465. };
  70466. var configFileUrl = jsonUrl + "/config.json";
  70467. var xhr = new XMLHttpRequest();
  70468. xhr.open("GET", configFileUrl, true);
  70469. xhr.addEventListener("load", function () {
  70470. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70471. try {
  70472. _this._config = JSON.parse(xhr.response);
  70473. _this.updateShaderUniforms();
  70474. _this.updateTextures();
  70475. _this.setFragment(_this._texturePath + "/custom");
  70476. _this._animate = _this._config.animate;
  70477. _this.refreshRate = _this._config.refreshrate;
  70478. }
  70479. catch (ex) {
  70480. noConfigFile();
  70481. }
  70482. }
  70483. else {
  70484. noConfigFile();
  70485. }
  70486. }, false);
  70487. xhr.addEventListener("error", function () {
  70488. noConfigFile();
  70489. }, false);
  70490. try {
  70491. xhr.send();
  70492. }
  70493. catch (ex) {
  70494. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70495. }
  70496. };
  70497. CustomProceduralTexture.prototype.isReady = function () {
  70498. if (!_super.prototype.isReady.call(this)) {
  70499. return false;
  70500. }
  70501. for (var name in this._textures) {
  70502. var texture = this._textures[name];
  70503. if (!texture.isReady()) {
  70504. return false;
  70505. }
  70506. }
  70507. return true;
  70508. };
  70509. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70510. var scene = this.getScene();
  70511. if (this._animate && scene) {
  70512. this._time += scene.getAnimationRatio() * 0.03;
  70513. this.updateShaderUniforms();
  70514. }
  70515. _super.prototype.render.call(this, useCameraPostProcess);
  70516. };
  70517. CustomProceduralTexture.prototype.updateTextures = function () {
  70518. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70519. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70520. }
  70521. };
  70522. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70523. if (this._config) {
  70524. for (var j = 0; j < this._config.uniforms.length; j++) {
  70525. var uniform = this._config.uniforms[j];
  70526. switch (uniform.type) {
  70527. case "float":
  70528. this.setFloat(uniform.name, uniform.value);
  70529. break;
  70530. case "color3":
  70531. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70532. break;
  70533. case "color4":
  70534. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70535. break;
  70536. case "vector2":
  70537. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70538. break;
  70539. case "vector3":
  70540. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70541. break;
  70542. }
  70543. }
  70544. }
  70545. this.setFloat("time", this._time);
  70546. };
  70547. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70548. get: function () {
  70549. return this._animate;
  70550. },
  70551. set: function (value) {
  70552. this._animate = value;
  70553. },
  70554. enumerable: true,
  70555. configurable: true
  70556. });
  70557. return CustomProceduralTexture;
  70558. }(BABYLON.ProceduralTexture));
  70559. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70560. })(BABYLON || (BABYLON = {}));
  70561. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70562. var BABYLON;
  70563. (function (BABYLON) {
  70564. var FreeCameraGamepadInput = /** @class */ (function () {
  70565. function FreeCameraGamepadInput() {
  70566. this.gamepadAngularSensibility = 200;
  70567. this.gamepadMoveSensibility = 40;
  70568. // private members
  70569. this._cameraTransform = BABYLON.Matrix.Identity();
  70570. this._deltaTransform = BABYLON.Vector3.Zero();
  70571. this._vector3 = BABYLON.Vector3.Zero();
  70572. this._vector2 = BABYLON.Vector2.Zero();
  70573. }
  70574. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70575. var _this = this;
  70576. var manager = this.camera.getScene().gamepadManager;
  70577. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70578. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70579. // prioritize XBOX gamepads.
  70580. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70581. _this.gamepad = gamepad;
  70582. }
  70583. }
  70584. });
  70585. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70586. if (_this.gamepad === gamepad) {
  70587. _this.gamepad = null;
  70588. }
  70589. });
  70590. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70591. };
  70592. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70593. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70594. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70595. this.gamepad = null;
  70596. };
  70597. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70598. if (this.gamepad && this.gamepad.leftStick) {
  70599. var camera = this.camera;
  70600. var LSValues = this.gamepad.leftStick;
  70601. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70602. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70603. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70604. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70605. var RSValues = this.gamepad.rightStick;
  70606. if (RSValues) {
  70607. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70608. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70609. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70610. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70611. }
  70612. else {
  70613. RSValues = { x: 0, y: 0 };
  70614. }
  70615. if (!camera.rotationQuaternion) {
  70616. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70617. }
  70618. else {
  70619. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70620. }
  70621. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70622. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70623. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70624. camera.cameraDirection.addInPlace(this._deltaTransform);
  70625. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70626. camera.cameraRotation.addInPlace(this._vector2);
  70627. }
  70628. };
  70629. FreeCameraGamepadInput.prototype.getClassName = function () {
  70630. return "FreeCameraGamepadInput";
  70631. };
  70632. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70633. return "gamepad";
  70634. };
  70635. __decorate([
  70636. BABYLON.serialize()
  70637. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70638. __decorate([
  70639. BABYLON.serialize()
  70640. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70641. return FreeCameraGamepadInput;
  70642. }());
  70643. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70644. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70645. })(BABYLON || (BABYLON = {}));
  70646. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70647. var BABYLON;
  70648. (function (BABYLON) {
  70649. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70650. function ArcRotateCameraGamepadInput() {
  70651. this.gamepadRotationSensibility = 80;
  70652. this.gamepadMoveSensibility = 40;
  70653. }
  70654. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70655. var _this = this;
  70656. var manager = this.camera.getScene().gamepadManager;
  70657. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70658. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70659. // prioritize XBOX gamepads.
  70660. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70661. _this.gamepad = gamepad;
  70662. }
  70663. }
  70664. });
  70665. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70666. if (_this.gamepad === gamepad) {
  70667. _this.gamepad = null;
  70668. }
  70669. });
  70670. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70671. };
  70672. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70673. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70674. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70675. this.gamepad = null;
  70676. };
  70677. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70678. if (this.gamepad) {
  70679. var camera = this.camera;
  70680. var RSValues = this.gamepad.rightStick;
  70681. if (RSValues) {
  70682. if (RSValues.x != 0) {
  70683. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70684. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70685. camera.inertialAlphaOffset += normalizedRX;
  70686. }
  70687. }
  70688. if (RSValues.y != 0) {
  70689. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70690. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70691. camera.inertialBetaOffset += normalizedRY;
  70692. }
  70693. }
  70694. }
  70695. var LSValues = this.gamepad.leftStick;
  70696. if (LSValues && LSValues.y != 0) {
  70697. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70698. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70699. this.camera.inertialRadiusOffset -= normalizedLY;
  70700. }
  70701. }
  70702. }
  70703. };
  70704. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70705. return "ArcRotateCameraGamepadInput";
  70706. };
  70707. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70708. return "gamepad";
  70709. };
  70710. __decorate([
  70711. BABYLON.serialize()
  70712. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70713. __decorate([
  70714. BABYLON.serialize()
  70715. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70716. return ArcRotateCameraGamepadInput;
  70717. }());
  70718. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70719. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70720. })(BABYLON || (BABYLON = {}));
  70721. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70722. var BABYLON;
  70723. (function (BABYLON) {
  70724. var GamepadManager = /** @class */ (function () {
  70725. function GamepadManager(_scene) {
  70726. var _this = this;
  70727. this._scene = _scene;
  70728. this._babylonGamepads = [];
  70729. this._oneGamepadConnected = false;
  70730. this._isMonitoring = false;
  70731. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70732. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70733. this._gamepadEventSupported = false;
  70734. }
  70735. else {
  70736. this._gamepadEventSupported = 'GamepadEvent' in window;
  70737. this._gamepadSupport = (navigator.getGamepads ||
  70738. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70739. }
  70740. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70741. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70742. for (var i in _this._babylonGamepads) {
  70743. var gamepad = _this._babylonGamepads[i];
  70744. if (gamepad && gamepad._isConnected) {
  70745. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70746. }
  70747. }
  70748. });
  70749. this._onGamepadConnectedEvent = function (evt) {
  70750. var gamepad = evt.gamepad;
  70751. if (gamepad.index in _this._babylonGamepads) {
  70752. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70753. return;
  70754. }
  70755. }
  70756. var newGamepad;
  70757. if (_this._babylonGamepads[gamepad.index]) {
  70758. newGamepad = _this._babylonGamepads[gamepad.index];
  70759. newGamepad.browserGamepad = gamepad;
  70760. newGamepad._isConnected = true;
  70761. }
  70762. else {
  70763. newGamepad = _this._addNewGamepad(gamepad);
  70764. }
  70765. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70766. _this._startMonitoringGamepads();
  70767. };
  70768. this._onGamepadDisconnectedEvent = function (evt) {
  70769. var gamepad = evt.gamepad;
  70770. // Remove the gamepad from the list of gamepads to monitor.
  70771. for (var i in _this._babylonGamepads) {
  70772. if (_this._babylonGamepads[i].index === gamepad.index) {
  70773. var disconnectedGamepad = _this._babylonGamepads[i];
  70774. disconnectedGamepad._isConnected = false;
  70775. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70776. break;
  70777. }
  70778. }
  70779. };
  70780. if (this._gamepadSupport) {
  70781. //first add already-connected gamepads
  70782. this._updateGamepadObjects();
  70783. if (this._babylonGamepads.length) {
  70784. this._startMonitoringGamepads();
  70785. }
  70786. // Checking if the gamepad connected event is supported (like in Firefox)
  70787. if (this._gamepadEventSupported) {
  70788. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70789. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70790. }
  70791. else {
  70792. this._startMonitoringGamepads();
  70793. }
  70794. }
  70795. }
  70796. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70797. get: function () {
  70798. return this._babylonGamepads;
  70799. },
  70800. enumerable: true,
  70801. configurable: true
  70802. });
  70803. GamepadManager.prototype.getGamepadByType = function (type) {
  70804. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70805. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70806. var gamepad = _a[_i];
  70807. if (gamepad && gamepad.type === type) {
  70808. return gamepad;
  70809. }
  70810. }
  70811. return null;
  70812. };
  70813. GamepadManager.prototype.dispose = function () {
  70814. if (this._gamepadEventSupported) {
  70815. if (this._onGamepadConnectedEvent) {
  70816. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70817. }
  70818. if (this._onGamepadDisconnectedEvent) {
  70819. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70820. }
  70821. this._onGamepadConnectedEvent = null;
  70822. this._onGamepadDisconnectedEvent = null;
  70823. }
  70824. this._babylonGamepads.forEach(function (gamepad) {
  70825. gamepad.dispose();
  70826. });
  70827. this.onGamepadConnectedObservable.clear();
  70828. this.onGamepadDisconnectedObservable.clear();
  70829. this._oneGamepadConnected = false;
  70830. this._stopMonitoringGamepads();
  70831. this._babylonGamepads = [];
  70832. };
  70833. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70834. if (!this._oneGamepadConnected) {
  70835. this._oneGamepadConnected = true;
  70836. }
  70837. var newGamepad;
  70838. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70839. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70840. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70841. }
  70842. // if pose is supported, use the (WebVR) pose enabled controller
  70843. else if (gamepad.pose) {
  70844. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70845. }
  70846. else {
  70847. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70848. }
  70849. this._babylonGamepads[newGamepad.index] = newGamepad;
  70850. return newGamepad;
  70851. };
  70852. GamepadManager.prototype._startMonitoringGamepads = function () {
  70853. if (!this._isMonitoring) {
  70854. this._isMonitoring = true;
  70855. //back-comp
  70856. if (!this._scene) {
  70857. this._checkGamepadsStatus();
  70858. }
  70859. }
  70860. };
  70861. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70862. this._isMonitoring = false;
  70863. };
  70864. GamepadManager.prototype._checkGamepadsStatus = function () {
  70865. var _this = this;
  70866. // Hack to be compatible Chrome
  70867. this._updateGamepadObjects();
  70868. for (var i in this._babylonGamepads) {
  70869. var gamepad = this._babylonGamepads[i];
  70870. if (!gamepad || !gamepad.isConnected) {
  70871. continue;
  70872. }
  70873. gamepad.update();
  70874. }
  70875. if (this._isMonitoring && !this._scene) {
  70876. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70877. }
  70878. };
  70879. // This function is called only on Chrome, which does not properly support
  70880. // connection/disconnection events and forces you to recopy again the gamepad object
  70881. GamepadManager.prototype._updateGamepadObjects = function () {
  70882. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70883. for (var i = 0; i < gamepads.length; i++) {
  70884. var gamepad = gamepads[i];
  70885. if (gamepad) {
  70886. if (!this._babylonGamepads[gamepad.index]) {
  70887. var newGamepad = this._addNewGamepad(gamepad);
  70888. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70889. }
  70890. else {
  70891. // Forced to copy again this object for Chrome for unknown reason
  70892. this._babylonGamepads[i].browserGamepad = gamepad;
  70893. if (!this._babylonGamepads[i].isConnected) {
  70894. this._babylonGamepads[i]._isConnected = true;
  70895. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70896. }
  70897. }
  70898. }
  70899. }
  70900. };
  70901. return GamepadManager;
  70902. }());
  70903. BABYLON.GamepadManager = GamepadManager;
  70904. })(BABYLON || (BABYLON = {}));
  70905. //# sourceMappingURL=babylon.gamepadManager.js.map
  70906. var BABYLON;
  70907. (function (BABYLON) {
  70908. var StickValues = /** @class */ (function () {
  70909. function StickValues(x, y) {
  70910. this.x = x;
  70911. this.y = y;
  70912. }
  70913. return StickValues;
  70914. }());
  70915. BABYLON.StickValues = StickValues;
  70916. var Gamepad = /** @class */ (function () {
  70917. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70918. if (leftStickX === void 0) { leftStickX = 0; }
  70919. if (leftStickY === void 0) { leftStickY = 1; }
  70920. if (rightStickX === void 0) { rightStickX = 2; }
  70921. if (rightStickY === void 0) { rightStickY = 3; }
  70922. this.id = id;
  70923. this.index = index;
  70924. this.browserGamepad = browserGamepad;
  70925. this._isConnected = true;
  70926. this._invertLeftStickY = false;
  70927. this.type = Gamepad.GAMEPAD;
  70928. this._leftStickAxisX = leftStickX;
  70929. this._leftStickAxisY = leftStickY;
  70930. this._rightStickAxisX = rightStickX;
  70931. this._rightStickAxisY = rightStickY;
  70932. if (this.browserGamepad.axes.length >= 2) {
  70933. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70934. }
  70935. if (this.browserGamepad.axes.length >= 4) {
  70936. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70937. }
  70938. }
  70939. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70940. get: function () {
  70941. return this._isConnected;
  70942. },
  70943. enumerable: true,
  70944. configurable: true
  70945. });
  70946. Gamepad.prototype.onleftstickchanged = function (callback) {
  70947. this._onleftstickchanged = callback;
  70948. };
  70949. Gamepad.prototype.onrightstickchanged = function (callback) {
  70950. this._onrightstickchanged = callback;
  70951. };
  70952. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70953. get: function () {
  70954. return this._leftStick;
  70955. },
  70956. set: function (newValues) {
  70957. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70958. this._onleftstickchanged(newValues);
  70959. }
  70960. this._leftStick = newValues;
  70961. },
  70962. enumerable: true,
  70963. configurable: true
  70964. });
  70965. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70966. get: function () {
  70967. return this._rightStick;
  70968. },
  70969. set: function (newValues) {
  70970. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70971. this._onrightstickchanged(newValues);
  70972. }
  70973. this._rightStick = newValues;
  70974. },
  70975. enumerable: true,
  70976. configurable: true
  70977. });
  70978. Gamepad.prototype.update = function () {
  70979. if (this._leftStick) {
  70980. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70981. if (this._invertLeftStickY) {
  70982. this.leftStick.y *= -1;
  70983. }
  70984. }
  70985. if (this._rightStick) {
  70986. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70987. }
  70988. };
  70989. Gamepad.prototype.dispose = function () {
  70990. };
  70991. Gamepad.GAMEPAD = 0;
  70992. Gamepad.GENERIC = 1;
  70993. Gamepad.XBOX = 2;
  70994. Gamepad.POSE_ENABLED = 3;
  70995. return Gamepad;
  70996. }());
  70997. BABYLON.Gamepad = Gamepad;
  70998. var GenericPad = /** @class */ (function (_super) {
  70999. __extends(GenericPad, _super);
  71000. function GenericPad(id, index, browserGamepad) {
  71001. var _this = _super.call(this, id, index, browserGamepad) || this;
  71002. _this.onButtonDownObservable = new BABYLON.Observable();
  71003. _this.onButtonUpObservable = new BABYLON.Observable();
  71004. _this.type = Gamepad.GENERIC;
  71005. _this._buttons = new Array(browserGamepad.buttons.length);
  71006. return _this;
  71007. }
  71008. GenericPad.prototype.onbuttondown = function (callback) {
  71009. this._onbuttondown = callback;
  71010. };
  71011. GenericPad.prototype.onbuttonup = function (callback) {
  71012. this._onbuttonup = callback;
  71013. };
  71014. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71015. if (newValue !== currentValue) {
  71016. if (newValue === 1) {
  71017. if (this._onbuttondown) {
  71018. this._onbuttondown(buttonIndex);
  71019. }
  71020. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71021. }
  71022. if (newValue === 0) {
  71023. if (this._onbuttonup) {
  71024. this._onbuttonup(buttonIndex);
  71025. }
  71026. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71027. }
  71028. }
  71029. return newValue;
  71030. };
  71031. GenericPad.prototype.update = function () {
  71032. _super.prototype.update.call(this);
  71033. for (var index = 0; index < this._buttons.length; index++) {
  71034. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71035. }
  71036. };
  71037. GenericPad.prototype.dispose = function () {
  71038. _super.prototype.dispose.call(this);
  71039. this.onButtonDownObservable.clear();
  71040. this.onButtonUpObservable.clear();
  71041. };
  71042. return GenericPad;
  71043. }(Gamepad));
  71044. BABYLON.GenericPad = GenericPad;
  71045. })(BABYLON || (BABYLON = {}));
  71046. //# sourceMappingURL=babylon.gamepad.js.map
  71047. var BABYLON;
  71048. (function (BABYLON) {
  71049. /**
  71050. * Defines supported buttons for XBox360 compatible gamepads
  71051. */
  71052. var Xbox360Button;
  71053. (function (Xbox360Button) {
  71054. /** A */
  71055. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71056. /** B */
  71057. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71058. /** X */
  71059. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71060. /** Y */
  71061. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71062. /** Start */
  71063. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71064. /** Back */
  71065. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71066. /** Left button */
  71067. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71068. /** Right button */
  71069. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71070. /** Left stick */
  71071. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71072. /** Right stick */
  71073. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71074. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71075. /** Defines values for XBox360 DPad */
  71076. var Xbox360Dpad;
  71077. (function (Xbox360Dpad) {
  71078. /** Up */
  71079. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71080. /** Down */
  71081. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71082. /** Left */
  71083. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71084. /** Right */
  71085. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71086. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71087. /**
  71088. * Defines a XBox360 gamepad
  71089. */
  71090. var Xbox360Pad = /** @class */ (function (_super) {
  71091. __extends(Xbox360Pad, _super);
  71092. /**
  71093. * Creates a new XBox360 gamepad object
  71094. * @param id defines the id of this gamepad
  71095. * @param index defines its index
  71096. * @param gamepad defines the internal HTML gamepad object
  71097. * @param xboxOne defines if it is a XBox One gamepad
  71098. */
  71099. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71100. if (xboxOne === void 0) { xboxOne = false; }
  71101. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71102. _this._leftTrigger = 0;
  71103. _this._rightTrigger = 0;
  71104. /** Observable raised when a button is pressed */
  71105. _this.onButtonDownObservable = new BABYLON.Observable();
  71106. /** Observable raised when a button is released */
  71107. _this.onButtonUpObservable = new BABYLON.Observable();
  71108. /** Observable raised when a pad is pressed */
  71109. _this.onPadDownObservable = new BABYLON.Observable();
  71110. /** Observable raised when a pad is released */
  71111. _this.onPadUpObservable = new BABYLON.Observable();
  71112. _this._buttonA = 0;
  71113. _this._buttonB = 0;
  71114. _this._buttonX = 0;
  71115. _this._buttonY = 0;
  71116. _this._buttonBack = 0;
  71117. _this._buttonStart = 0;
  71118. _this._buttonLB = 0;
  71119. _this._buttonRB = 0;
  71120. _this._buttonLeftStick = 0;
  71121. _this._buttonRightStick = 0;
  71122. _this._dPadUp = 0;
  71123. _this._dPadDown = 0;
  71124. _this._dPadLeft = 0;
  71125. _this._dPadRight = 0;
  71126. _this._isXboxOnePad = false;
  71127. _this.type = BABYLON.Gamepad.XBOX;
  71128. _this._isXboxOnePad = xboxOne;
  71129. return _this;
  71130. }
  71131. /**
  71132. * Defines the callback to call when left trigger is pressed
  71133. * @param callback defines the callback to use
  71134. */
  71135. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71136. this._onlefttriggerchanged = callback;
  71137. };
  71138. /**
  71139. * Defines the callback to call when right trigger is pressed
  71140. * @param callback defines the callback to use
  71141. */
  71142. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71143. this._onrighttriggerchanged = callback;
  71144. };
  71145. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71146. /**
  71147. * Gets or sets left trigger value
  71148. */
  71149. get: function () {
  71150. return this._leftTrigger;
  71151. },
  71152. set: function (newValue) {
  71153. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71154. this._onlefttriggerchanged(newValue);
  71155. }
  71156. this._leftTrigger = newValue;
  71157. },
  71158. enumerable: true,
  71159. configurable: true
  71160. });
  71161. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71162. /**
  71163. * Gets or sets right trigger value
  71164. */
  71165. get: function () {
  71166. return this._rightTrigger;
  71167. },
  71168. set: function (newValue) {
  71169. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71170. this._onrighttriggerchanged(newValue);
  71171. }
  71172. this._rightTrigger = newValue;
  71173. },
  71174. enumerable: true,
  71175. configurable: true
  71176. });
  71177. /**
  71178. * Defines the callback to call when a button is pressed
  71179. * @param callback defines the callback to use
  71180. */
  71181. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71182. this._onbuttondown = callback;
  71183. };
  71184. /**
  71185. * Defines the callback to call when a button is released
  71186. * @param callback defines the callback to use
  71187. */
  71188. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71189. this._onbuttonup = callback;
  71190. };
  71191. /**
  71192. * Defines the callback to call when a pad is pressed
  71193. * @param callback defines the callback to use
  71194. */
  71195. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71196. this._ondpaddown = callback;
  71197. };
  71198. /**
  71199. * Defines the callback to call when a pad is released
  71200. * @param callback defines the callback to use
  71201. */
  71202. Xbox360Pad.prototype.ondpadup = function (callback) {
  71203. this._ondpadup = callback;
  71204. };
  71205. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71206. if (newValue !== currentValue) {
  71207. if (newValue === 1) {
  71208. if (this._onbuttondown) {
  71209. this._onbuttondown(buttonType);
  71210. }
  71211. this.onButtonDownObservable.notifyObservers(buttonType);
  71212. }
  71213. if (newValue === 0) {
  71214. if (this._onbuttonup) {
  71215. this._onbuttonup(buttonType);
  71216. }
  71217. this.onButtonUpObservable.notifyObservers(buttonType);
  71218. }
  71219. }
  71220. return newValue;
  71221. };
  71222. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71223. if (newValue !== currentValue) {
  71224. if (newValue === 1) {
  71225. if (this._ondpaddown) {
  71226. this._ondpaddown(buttonType);
  71227. }
  71228. this.onPadDownObservable.notifyObservers(buttonType);
  71229. }
  71230. if (newValue === 0) {
  71231. if (this._ondpadup) {
  71232. this._ondpadup(buttonType);
  71233. }
  71234. this.onPadUpObservable.notifyObservers(buttonType);
  71235. }
  71236. }
  71237. return newValue;
  71238. };
  71239. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71240. /** Gets or sets value of A button */
  71241. get: function () {
  71242. return this._buttonA;
  71243. },
  71244. set: function (value) {
  71245. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71246. },
  71247. enumerable: true,
  71248. configurable: true
  71249. });
  71250. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71251. /** Gets or sets value of B button */
  71252. get: function () {
  71253. return this._buttonB;
  71254. },
  71255. set: function (value) {
  71256. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71257. },
  71258. enumerable: true,
  71259. configurable: true
  71260. });
  71261. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71262. /** Gets or sets value of X button */
  71263. get: function () {
  71264. return this._buttonX;
  71265. },
  71266. set: function (value) {
  71267. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71268. },
  71269. enumerable: true,
  71270. configurable: true
  71271. });
  71272. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71273. /** Gets or sets value of Y button */
  71274. get: function () {
  71275. return this._buttonY;
  71276. },
  71277. set: function (value) {
  71278. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71279. },
  71280. enumerable: true,
  71281. configurable: true
  71282. });
  71283. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71284. /** Gets or sets value of Start button */
  71285. get: function () {
  71286. return this._buttonStart;
  71287. },
  71288. set: function (value) {
  71289. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71290. },
  71291. enumerable: true,
  71292. configurable: true
  71293. });
  71294. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71295. /** Gets or sets value of Back button */
  71296. get: function () {
  71297. return this._buttonBack;
  71298. },
  71299. set: function (value) {
  71300. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71301. },
  71302. enumerable: true,
  71303. configurable: true
  71304. });
  71305. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71306. /** Gets or sets value of Left button */
  71307. get: function () {
  71308. return this._buttonLB;
  71309. },
  71310. set: function (value) {
  71311. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71312. },
  71313. enumerable: true,
  71314. configurable: true
  71315. });
  71316. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71317. /** Gets or sets value of Right button */
  71318. get: function () {
  71319. return this._buttonRB;
  71320. },
  71321. set: function (value) {
  71322. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71323. },
  71324. enumerable: true,
  71325. configurable: true
  71326. });
  71327. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71328. /** Gets or sets value of left stick */
  71329. get: function () {
  71330. return this._buttonLeftStick;
  71331. },
  71332. set: function (value) {
  71333. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71334. },
  71335. enumerable: true,
  71336. configurable: true
  71337. });
  71338. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71339. /** Gets or sets value of right stick */
  71340. get: function () {
  71341. return this._buttonRightStick;
  71342. },
  71343. set: function (value) {
  71344. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71345. },
  71346. enumerable: true,
  71347. configurable: true
  71348. });
  71349. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71350. /** Gets or sets value of DPad up */
  71351. get: function () {
  71352. return this._dPadUp;
  71353. },
  71354. set: function (value) {
  71355. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71356. },
  71357. enumerable: true,
  71358. configurable: true
  71359. });
  71360. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71361. /** Gets or sets value of DPad down */
  71362. get: function () {
  71363. return this._dPadDown;
  71364. },
  71365. set: function (value) {
  71366. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71367. },
  71368. enumerable: true,
  71369. configurable: true
  71370. });
  71371. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71372. /** Gets or sets value of DPad left */
  71373. get: function () {
  71374. return this._dPadLeft;
  71375. },
  71376. set: function (value) {
  71377. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71378. },
  71379. enumerable: true,
  71380. configurable: true
  71381. });
  71382. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71383. /** Gets or sets value of DPad right */
  71384. get: function () {
  71385. return this._dPadRight;
  71386. },
  71387. set: function (value) {
  71388. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71389. },
  71390. enumerable: true,
  71391. configurable: true
  71392. });
  71393. /**
  71394. * Force the gamepad to synchronize with device values
  71395. */
  71396. Xbox360Pad.prototype.update = function () {
  71397. _super.prototype.update.call(this);
  71398. if (this._isXboxOnePad) {
  71399. this.buttonA = this.browserGamepad.buttons[0].value;
  71400. this.buttonB = this.browserGamepad.buttons[1].value;
  71401. this.buttonX = this.browserGamepad.buttons[2].value;
  71402. this.buttonY = this.browserGamepad.buttons[3].value;
  71403. this.buttonLB = this.browserGamepad.buttons[4].value;
  71404. this.buttonRB = this.browserGamepad.buttons[5].value;
  71405. this.leftTrigger = this.browserGamepad.axes[2];
  71406. this.rightTrigger = this.browserGamepad.axes[5];
  71407. this.buttonBack = this.browserGamepad.buttons[9].value;
  71408. this.buttonStart = this.browserGamepad.buttons[8].value;
  71409. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71410. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71411. this.dPadUp = this.browserGamepad.buttons[11].value;
  71412. this.dPadDown = this.browserGamepad.buttons[12].value;
  71413. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71414. this.dPadRight = this.browserGamepad.buttons[14].value;
  71415. }
  71416. else {
  71417. this.buttonA = this.browserGamepad.buttons[0].value;
  71418. this.buttonB = this.browserGamepad.buttons[1].value;
  71419. this.buttonX = this.browserGamepad.buttons[2].value;
  71420. this.buttonY = this.browserGamepad.buttons[3].value;
  71421. this.buttonLB = this.browserGamepad.buttons[4].value;
  71422. this.buttonRB = this.browserGamepad.buttons[5].value;
  71423. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71424. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71425. this.buttonBack = this.browserGamepad.buttons[8].value;
  71426. this.buttonStart = this.browserGamepad.buttons[9].value;
  71427. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71428. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71429. this.dPadUp = this.browserGamepad.buttons[12].value;
  71430. this.dPadDown = this.browserGamepad.buttons[13].value;
  71431. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71432. this.dPadRight = this.browserGamepad.buttons[15].value;
  71433. }
  71434. };
  71435. Xbox360Pad.prototype.dispose = function () {
  71436. _super.prototype.dispose.call(this);
  71437. this.onButtonDownObservable.clear();
  71438. this.onButtonUpObservable.clear();
  71439. this.onPadDownObservable.clear();
  71440. this.onPadUpObservable.clear();
  71441. };
  71442. return Xbox360Pad;
  71443. }(BABYLON.Gamepad));
  71444. BABYLON.Xbox360Pad = Xbox360Pad;
  71445. })(BABYLON || (BABYLON = {}));
  71446. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71447. var BABYLON;
  71448. (function (BABYLON) {
  71449. /**
  71450. * Defines the types of pose enabled controllers that are supported
  71451. */
  71452. var PoseEnabledControllerType;
  71453. (function (PoseEnabledControllerType) {
  71454. /**
  71455. * HTC Vive
  71456. */
  71457. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71458. /**
  71459. * Oculus Rift
  71460. */
  71461. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71462. /**
  71463. * Windows mixed reality
  71464. */
  71465. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71466. /**
  71467. * Samsung gear VR
  71468. */
  71469. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71470. /**
  71471. * Google Daydream
  71472. */
  71473. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71474. /**
  71475. * Generic
  71476. */
  71477. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71478. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71479. /**
  71480. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71481. */
  71482. var PoseEnabledControllerHelper = /** @class */ (function () {
  71483. function PoseEnabledControllerHelper() {
  71484. }
  71485. /**
  71486. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71487. * @param vrGamepad the gamepad to initialized
  71488. * @returns a vr controller of the type the gamepad identified as
  71489. */
  71490. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71491. // Oculus Touch
  71492. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71493. return new BABYLON.OculusTouchController(vrGamepad);
  71494. }
  71495. // Windows Mixed Reality controllers
  71496. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71497. return new BABYLON.WindowsMotionController(vrGamepad);
  71498. }
  71499. // HTC Vive
  71500. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71501. return new BABYLON.ViveController(vrGamepad);
  71502. }
  71503. // Samsung/Oculus Gear VR or Oculus Go
  71504. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71505. return new BABYLON.GearVRController(vrGamepad);
  71506. }
  71507. // Google Daydream
  71508. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71509. return new BABYLON.DaydreamController(vrGamepad);
  71510. }
  71511. // Generic
  71512. else {
  71513. return new BABYLON.GenericController(vrGamepad);
  71514. }
  71515. };
  71516. return PoseEnabledControllerHelper;
  71517. }());
  71518. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71519. /**
  71520. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71521. */
  71522. var PoseEnabledController = /** @class */ (function (_super) {
  71523. __extends(PoseEnabledController, _super);
  71524. /**
  71525. * Creates a new PoseEnabledController from a gamepad
  71526. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71527. */
  71528. function PoseEnabledController(browserGamepad) {
  71529. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71530. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71531. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71532. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71533. /**
  71534. * The device position in babylon space
  71535. */
  71536. _this.devicePosition = BABYLON.Vector3.Zero();
  71537. /**
  71538. * The device rotation in babylon space
  71539. */
  71540. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71541. /**
  71542. * The scale factor of the device in babylon space
  71543. */
  71544. _this.deviceScaleFactor = 1;
  71545. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71546. /**
  71547. * Internal, matrix used to convert room space to babylon space
  71548. */
  71549. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71550. /**
  71551. * Node to be used when casting a ray from the controller
  71552. */
  71553. _this._pointingPoseNode = null;
  71554. _this._workingMatrix = BABYLON.Matrix.Identity();
  71555. /**
  71556. * @hidden
  71557. */
  71558. _this._meshAttachedObservable = new BABYLON.Observable();
  71559. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71560. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71561. _this.position = BABYLON.Vector3.Zero();
  71562. _this.rotationQuaternion = new BABYLON.Quaternion();
  71563. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71564. _this._calculatedRotation = new BABYLON.Quaternion();
  71565. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71566. return _this;
  71567. }
  71568. /**
  71569. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71570. */
  71571. PoseEnabledController.prototype.update = function () {
  71572. _super.prototype.update.call(this);
  71573. var pose = this.browserGamepad.pose;
  71574. this.updateFromDevice(pose);
  71575. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71576. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71577. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71578. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71579. if (this._mesh) {
  71580. this._mesh.position.copyFrom(this.devicePosition);
  71581. if (this._mesh.rotationQuaternion) {
  71582. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71583. }
  71584. }
  71585. };
  71586. /**
  71587. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71588. * @param poseData raw pose fromthe device
  71589. */
  71590. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71591. if (poseData) {
  71592. this.rawPose = poseData;
  71593. if (poseData.position) {
  71594. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71595. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71596. this._deviceRoomPosition.z *= -1;
  71597. }
  71598. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71599. this._calculatedPosition.addInPlace(this.position);
  71600. }
  71601. var pose = this.rawPose;
  71602. if (poseData.orientation && pose.orientation) {
  71603. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71604. if (this._mesh) {
  71605. if (this._mesh.getScene().useRightHandedSystem) {
  71606. this._deviceRoomRotationQuaternion.z *= -1;
  71607. this._deviceRoomRotationQuaternion.w *= -1;
  71608. }
  71609. else {
  71610. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71611. }
  71612. }
  71613. // if the camera is set, rotate to the camera's rotation
  71614. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71615. }
  71616. }
  71617. };
  71618. /**
  71619. * Attaches a mesh to the controller
  71620. * @param mesh the mesh to be attached
  71621. */
  71622. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71623. if (this._mesh) {
  71624. this._mesh.parent = null;
  71625. }
  71626. this._mesh = mesh;
  71627. if (this._poseControlledCamera) {
  71628. this._mesh.parent = this._poseControlledCamera;
  71629. }
  71630. if (!this._mesh.rotationQuaternion) {
  71631. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71632. }
  71633. this._meshAttachedObservable.notifyObservers(mesh);
  71634. };
  71635. /**
  71636. * Attaches the controllers mesh to a camera
  71637. * @param camera the camera the mesh should be attached to
  71638. */
  71639. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71640. this._poseControlledCamera = camera;
  71641. if (this._mesh) {
  71642. this._mesh.parent = this._poseControlledCamera;
  71643. }
  71644. };
  71645. /**
  71646. * Disposes of the controller
  71647. */
  71648. PoseEnabledController.prototype.dispose = function () {
  71649. if (this._mesh) {
  71650. this._mesh.dispose();
  71651. }
  71652. this._mesh = null;
  71653. _super.prototype.dispose.call(this);
  71654. };
  71655. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71656. /**
  71657. * The mesh that is attached to the controller
  71658. */
  71659. get: function () {
  71660. return this._mesh;
  71661. },
  71662. enumerable: true,
  71663. configurable: true
  71664. });
  71665. /**
  71666. * Gets the ray of the controller in the direction the controller is pointing
  71667. * @param length the length the resulting ray should be
  71668. * @returns a ray in the direction the controller is pointing
  71669. */
  71670. PoseEnabledController.prototype.getForwardRay = function (length) {
  71671. if (length === void 0) { length = 100; }
  71672. if (!this.mesh) {
  71673. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71674. }
  71675. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71676. var origin = m.getTranslation();
  71677. var forward = new BABYLON.Vector3(0, 0, -1);
  71678. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71679. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71680. return new BABYLON.Ray(origin, direction, length);
  71681. };
  71682. /**
  71683. * Name of the child mesh that can be used to cast a ray from the controller
  71684. */
  71685. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71686. return PoseEnabledController;
  71687. }(BABYLON.Gamepad));
  71688. BABYLON.PoseEnabledController = PoseEnabledController;
  71689. })(BABYLON || (BABYLON = {}));
  71690. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71691. var BABYLON;
  71692. (function (BABYLON) {
  71693. /**
  71694. * Defines the WebVRController object that represents controllers tracked in 3D space
  71695. */
  71696. var WebVRController = /** @class */ (function (_super) {
  71697. __extends(WebVRController, _super);
  71698. /**
  71699. * Creates a new WebVRController from a gamepad
  71700. * @param vrGamepad the gamepad that the WebVRController should be created from
  71701. */
  71702. function WebVRController(vrGamepad) {
  71703. var _this = _super.call(this, vrGamepad) || this;
  71704. // Observables
  71705. /**
  71706. * Fired when the trigger state has changed
  71707. */
  71708. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71709. /**
  71710. * Fired when the main button state has changed
  71711. */
  71712. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71713. /**
  71714. * Fired when the secondary button state has changed
  71715. */
  71716. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71717. /**
  71718. * Fired when the pad state has changed
  71719. */
  71720. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71721. /**
  71722. * Fired when controllers stick values have changed
  71723. */
  71724. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71725. /**
  71726. * X and Y axis corrisponding to the controllers joystick
  71727. */
  71728. _this.pad = { x: 0, y: 0 };
  71729. // avoid GC, store state in a tmp object
  71730. _this._changes = {
  71731. pressChanged: false,
  71732. touchChanged: false,
  71733. valueChanged: false,
  71734. changed: false
  71735. };
  71736. _this._buttons = new Array(vrGamepad.buttons.length);
  71737. _this.hand = vrGamepad.hand;
  71738. return _this;
  71739. }
  71740. /**
  71741. * Fired when a controller button's state has changed
  71742. * @param callback the callback containing the button that was modified
  71743. */
  71744. WebVRController.prototype.onButtonStateChange = function (callback) {
  71745. this._onButtonStateChange = callback;
  71746. };
  71747. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71748. /**
  71749. * The default controller model for the controller
  71750. */
  71751. get: function () {
  71752. return this._defaultModel;
  71753. },
  71754. enumerable: true,
  71755. configurable: true
  71756. });
  71757. /**
  71758. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71759. */
  71760. WebVRController.prototype.update = function () {
  71761. _super.prototype.update.call(this);
  71762. for (var index = 0; index < this._buttons.length; index++) {
  71763. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71764. }
  71765. ;
  71766. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71767. this.pad.x = this.leftStick.x;
  71768. this.pad.y = this.leftStick.y;
  71769. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71770. }
  71771. };
  71772. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71773. if (!newState) {
  71774. newState = {
  71775. pressed: false,
  71776. touched: false,
  71777. value: 0
  71778. };
  71779. }
  71780. if (!currentState) {
  71781. this._buttons[buttonIndex] = {
  71782. pressed: newState.pressed,
  71783. touched: newState.touched,
  71784. value: newState.value
  71785. };
  71786. return;
  71787. }
  71788. this._checkChanges(newState, currentState);
  71789. if (this._changes.changed) {
  71790. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71791. this._handleButtonChange(buttonIndex, newState, this._changes);
  71792. }
  71793. this._buttons[buttonIndex].pressed = newState.pressed;
  71794. this._buttons[buttonIndex].touched = newState.touched;
  71795. // oculus triggers are never 0, thou not touched.
  71796. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71797. };
  71798. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71799. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71800. this._changes.touchChanged = newState.touched !== currentState.touched;
  71801. this._changes.valueChanged = newState.value !== currentState.value;
  71802. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71803. return this._changes;
  71804. };
  71805. /**
  71806. * Disposes of th webVRCOntroller
  71807. */
  71808. WebVRController.prototype.dispose = function () {
  71809. _super.prototype.dispose.call(this);
  71810. this.onTriggerStateChangedObservable.clear();
  71811. this.onMainButtonStateChangedObservable.clear();
  71812. this.onSecondaryButtonStateChangedObservable.clear();
  71813. this.onPadStateChangedObservable.clear();
  71814. this.onPadValuesChangedObservable.clear();
  71815. };
  71816. return WebVRController;
  71817. }(BABYLON.PoseEnabledController));
  71818. BABYLON.WebVRController = WebVRController;
  71819. })(BABYLON || (BABYLON = {}));
  71820. //# sourceMappingURL=babylon.webVRController.js.map
  71821. var BABYLON;
  71822. (function (BABYLON) {
  71823. /**
  71824. * Oculus Touch Controller
  71825. */
  71826. var OculusTouchController = /** @class */ (function (_super) {
  71827. __extends(OculusTouchController, _super);
  71828. /**
  71829. * Creates a new OculusTouchController from a gamepad
  71830. * @param vrGamepad the gamepad that the controller should be created from
  71831. */
  71832. function OculusTouchController(vrGamepad) {
  71833. var _this = _super.call(this, vrGamepad) || this;
  71834. /**
  71835. * Fired when the secondary trigger on this controller is modified
  71836. */
  71837. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71838. /**
  71839. * Fired when the thumb rest on this controller is modified
  71840. */
  71841. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71842. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71843. return _this;
  71844. }
  71845. /**
  71846. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71847. * @param scene scene in which to add meshes
  71848. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71849. */
  71850. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71851. var _this = this;
  71852. var meshName;
  71853. // Hand
  71854. if (this.hand === 'left') {
  71855. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71856. }
  71857. else { // Right is the default if no hand is specified
  71858. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71859. }
  71860. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71861. /*
  71862. Parent Mesh name: oculus_touch_left
  71863. - body
  71864. - trigger
  71865. - thumbstick
  71866. - grip
  71867. - button_y
  71868. - button_x
  71869. - button_enter
  71870. */
  71871. _this._defaultModel = newMeshes[1];
  71872. _this.attachToMesh(_this._defaultModel);
  71873. if (meshLoaded) {
  71874. meshLoaded(_this._defaultModel);
  71875. }
  71876. });
  71877. };
  71878. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71879. /**
  71880. * Fired when the A button on this controller is modified
  71881. */
  71882. get: function () {
  71883. if (this.hand === 'right') {
  71884. return this.onMainButtonStateChangedObservable;
  71885. }
  71886. else {
  71887. throw new Error('No A button on left hand');
  71888. }
  71889. },
  71890. enumerable: true,
  71891. configurable: true
  71892. });
  71893. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71894. /**
  71895. * Fired when the B button on this controller is modified
  71896. */
  71897. get: function () {
  71898. if (this.hand === 'right') {
  71899. return this.onSecondaryButtonStateChangedObservable;
  71900. }
  71901. else {
  71902. throw new Error('No B button on left hand');
  71903. }
  71904. },
  71905. enumerable: true,
  71906. configurable: true
  71907. });
  71908. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71909. /**
  71910. * Fired when the X button on this controller is modified
  71911. */
  71912. get: function () {
  71913. if (this.hand === 'left') {
  71914. return this.onMainButtonStateChangedObservable;
  71915. }
  71916. else {
  71917. throw new Error('No X button on right hand');
  71918. }
  71919. },
  71920. enumerable: true,
  71921. configurable: true
  71922. });
  71923. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71924. /**
  71925. * Fired when the Y button on this controller is modified
  71926. */
  71927. get: function () {
  71928. if (this.hand === 'left') {
  71929. return this.onSecondaryButtonStateChangedObservable;
  71930. }
  71931. else {
  71932. throw new Error('No Y button on right hand');
  71933. }
  71934. },
  71935. enumerable: true,
  71936. configurable: true
  71937. });
  71938. /**
  71939. * Called once for each button that changed state since the last frame
  71940. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71941. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71942. * 2) secondary trigger (same)
  71943. * 3) A (right) X (left), touch, pressed = value
  71944. * 4) B / Y
  71945. * 5) thumb rest
  71946. * @param buttonIdx Which button index changed
  71947. * @param state New state of the button
  71948. * @param changes Which properties on the state changed since last frame
  71949. */
  71950. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71951. var notifyObject = state; //{ state: state, changes: changes };
  71952. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71953. switch (buttonIdx) {
  71954. case 0:
  71955. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71956. return;
  71957. case 1: // index trigger
  71958. if (this._defaultModel) {
  71959. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71960. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71961. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71962. }
  71963. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71964. return;
  71965. case 2: // secondary trigger
  71966. if (this._defaultModel) {
  71967. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71968. }
  71969. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71970. return;
  71971. case 3:
  71972. if (this._defaultModel) {
  71973. if (notifyObject.pressed) {
  71974. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71975. }
  71976. else {
  71977. (this._defaultModel.getChildren()[1]).position.y = 0;
  71978. }
  71979. }
  71980. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71981. return;
  71982. case 4:
  71983. if (this._defaultModel) {
  71984. if (notifyObject.pressed) {
  71985. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71986. }
  71987. else {
  71988. (this._defaultModel.getChildren()[2]).position.y = 0;
  71989. }
  71990. }
  71991. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71992. return;
  71993. case 5:
  71994. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71995. return;
  71996. }
  71997. };
  71998. /**
  71999. * Base Url for the controller model.
  72000. */
  72001. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72002. /**
  72003. * File name for the left controller model.
  72004. */
  72005. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72006. /**
  72007. * File name for the right controller model.
  72008. */
  72009. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72010. return OculusTouchController;
  72011. }(BABYLON.WebVRController));
  72012. BABYLON.OculusTouchController = OculusTouchController;
  72013. })(BABYLON || (BABYLON = {}));
  72014. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72015. var BABYLON;
  72016. (function (BABYLON) {
  72017. /**
  72018. * Vive Controller
  72019. */
  72020. var ViveController = /** @class */ (function (_super) {
  72021. __extends(ViveController, _super);
  72022. /**
  72023. * Creates a new ViveController from a gamepad
  72024. * @param vrGamepad the gamepad that the controller should be created from
  72025. */
  72026. function ViveController(vrGamepad) {
  72027. var _this = _super.call(this, vrGamepad) || this;
  72028. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72029. _this._invertLeftStickY = true;
  72030. return _this;
  72031. }
  72032. /**
  72033. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72034. * @param scene scene in which to add meshes
  72035. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72036. */
  72037. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72038. var _this = this;
  72039. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72040. /*
  72041. Parent Mesh name: ViveWand
  72042. - body
  72043. - r_gripper
  72044. - l_gripper
  72045. - menu_button
  72046. - system_button
  72047. - trackpad
  72048. - trigger
  72049. - LED
  72050. */
  72051. _this._defaultModel = newMeshes[1];
  72052. _this.attachToMesh(_this._defaultModel);
  72053. if (meshLoaded) {
  72054. meshLoaded(_this._defaultModel);
  72055. }
  72056. });
  72057. };
  72058. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72059. /**
  72060. * Fired when the left button on this controller is modified
  72061. */
  72062. get: function () {
  72063. return this.onMainButtonStateChangedObservable;
  72064. },
  72065. enumerable: true,
  72066. configurable: true
  72067. });
  72068. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72069. /**
  72070. * Fired when the right button on this controller is modified
  72071. */
  72072. get: function () {
  72073. return this.onMainButtonStateChangedObservable;
  72074. },
  72075. enumerable: true,
  72076. configurable: true
  72077. });
  72078. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72079. /**
  72080. * Fired when the menu button on this controller is modified
  72081. */
  72082. get: function () {
  72083. return this.onSecondaryButtonStateChangedObservable;
  72084. },
  72085. enumerable: true,
  72086. configurable: true
  72087. });
  72088. /**
  72089. * Called once for each button that changed state since the last frame
  72090. * Vive mapping:
  72091. * 0: touchpad
  72092. * 1: trigger
  72093. * 2: left AND right buttons
  72094. * 3: menu button
  72095. * @param buttonIdx Which button index changed
  72096. * @param state New state of the button
  72097. * @param changes Which properties on the state changed since last frame
  72098. */
  72099. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72100. var notifyObject = state; //{ state: state, changes: changes };
  72101. switch (buttonIdx) {
  72102. case 0:
  72103. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72104. return;
  72105. case 1: // index trigger
  72106. if (this._defaultModel) {
  72107. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72108. }
  72109. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72110. return;
  72111. case 2: // left AND right button
  72112. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72113. return;
  72114. case 3:
  72115. if (this._defaultModel) {
  72116. if (notifyObject.pressed) {
  72117. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72118. }
  72119. else {
  72120. (this._defaultModel.getChildren()[2]).position.y = 0;
  72121. }
  72122. }
  72123. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72124. return;
  72125. }
  72126. };
  72127. /**
  72128. * Base Url for the controller model.
  72129. */
  72130. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72131. /**
  72132. * File name for the controller model.
  72133. */
  72134. ViveController.MODEL_FILENAME = 'wand.babylon';
  72135. return ViveController;
  72136. }(BABYLON.WebVRController));
  72137. BABYLON.ViveController = ViveController;
  72138. })(BABYLON || (BABYLON = {}));
  72139. //# sourceMappingURL=babylon.viveController.js.map
  72140. var BABYLON;
  72141. (function (BABYLON) {
  72142. /**
  72143. * Generic Controller
  72144. */
  72145. var GenericController = /** @class */ (function (_super) {
  72146. __extends(GenericController, _super);
  72147. /**
  72148. * Creates a new GenericController from a gamepad
  72149. * @param vrGamepad the gamepad that the controller should be created from
  72150. */
  72151. function GenericController(vrGamepad) {
  72152. return _super.call(this, vrGamepad) || this;
  72153. }
  72154. /**
  72155. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72156. * @param scene scene in which to add meshes
  72157. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72158. */
  72159. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72160. var _this = this;
  72161. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72162. _this._defaultModel = newMeshes[1];
  72163. _this.attachToMesh(_this._defaultModel);
  72164. if (meshLoaded) {
  72165. meshLoaded(_this._defaultModel);
  72166. }
  72167. });
  72168. };
  72169. /**
  72170. * Called once for each button that changed state since the last frame
  72171. * @param buttonIdx Which button index changed
  72172. * @param state New state of the button
  72173. * @param changes Which properties on the state changed since last frame
  72174. */
  72175. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72176. console.log("Button id: " + buttonIdx + "state: ");
  72177. console.dir(state);
  72178. };
  72179. /**
  72180. * Base Url for the controller model.
  72181. */
  72182. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72183. /**
  72184. * File name for the controller model.
  72185. */
  72186. GenericController.MODEL_FILENAME = 'generic.babylon';
  72187. return GenericController;
  72188. }(BABYLON.WebVRController));
  72189. BABYLON.GenericController = GenericController;
  72190. })(BABYLON || (BABYLON = {}));
  72191. //# sourceMappingURL=babylon.genericController.js.map
  72192. var BABYLON;
  72193. (function (BABYLON) {
  72194. /**
  72195. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72196. */
  72197. var LoadedMeshInfo = /** @class */ (function () {
  72198. function LoadedMeshInfo() {
  72199. /**
  72200. * Map of the button meshes contained in the controller
  72201. */
  72202. this.buttonMeshes = {};
  72203. /**
  72204. * Map of the axis meshes contained in the controller
  72205. */
  72206. this.axisMeshes = {};
  72207. }
  72208. return LoadedMeshInfo;
  72209. }());
  72210. /**
  72211. * Defines the WindowsMotionController object that the state of the windows motion controller
  72212. */
  72213. var WindowsMotionController = /** @class */ (function (_super) {
  72214. __extends(WindowsMotionController, _super);
  72215. /**
  72216. * Creates a new WindowsMotionController from a gamepad
  72217. * @param vrGamepad the gamepad that the controller should be created from
  72218. */
  72219. function WindowsMotionController(vrGamepad) {
  72220. var _this = _super.call(this, vrGamepad) || this;
  72221. _this._mapping = {
  72222. // Semantic button names
  72223. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72224. // A mapping of the button name to glTF model node name
  72225. // that should be transformed by button value.
  72226. buttonMeshNames: {
  72227. 'trigger': 'SELECT',
  72228. 'menu': 'MENU',
  72229. 'grip': 'GRASP',
  72230. 'thumbstick': 'THUMBSTICK_PRESS',
  72231. 'trackpad': 'TOUCHPAD_PRESS'
  72232. },
  72233. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72234. buttonObservableNames: {
  72235. 'trigger': 'onTriggerStateChangedObservable',
  72236. 'menu': 'onSecondaryButtonStateChangedObservable',
  72237. 'grip': 'onMainButtonStateChangedObservable',
  72238. 'thumbstick': 'onPadStateChangedObservable',
  72239. 'trackpad': 'onTrackpadChangedObservable'
  72240. },
  72241. // A mapping of the axis name to glTF model node name
  72242. // that should be transformed by axis value.
  72243. // This array mirrors the browserGamepad.axes array, such that
  72244. // the mesh corresponding to axis 0 is in this array index 0.
  72245. axisMeshNames: [
  72246. 'THUMBSTICK_X',
  72247. 'THUMBSTICK_Y',
  72248. 'TOUCHPAD_TOUCH_X',
  72249. 'TOUCHPAD_TOUCH_Y'
  72250. ],
  72251. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72252. };
  72253. /**
  72254. * Fired when the trackpad on this controller is clicked
  72255. */
  72256. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72257. /**
  72258. * Fired when the trackpad on this controller is modified
  72259. */
  72260. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72261. /**
  72262. * The current x and y values of this controller's trackpad
  72263. */
  72264. _this.trackpad = { x: 0, y: 0 };
  72265. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72266. _this._loadedMeshInfo = null;
  72267. return _this;
  72268. }
  72269. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72270. /**
  72271. * Fired when the trigger on this controller is modified
  72272. */
  72273. get: function () {
  72274. return this.onTriggerStateChangedObservable;
  72275. },
  72276. enumerable: true,
  72277. configurable: true
  72278. });
  72279. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72280. /**
  72281. * Fired when the menu button on this controller is modified
  72282. */
  72283. get: function () {
  72284. return this.onSecondaryButtonStateChangedObservable;
  72285. },
  72286. enumerable: true,
  72287. configurable: true
  72288. });
  72289. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72290. /**
  72291. * Fired when the grip button on this controller is modified
  72292. */
  72293. get: function () {
  72294. return this.onMainButtonStateChangedObservable;
  72295. },
  72296. enumerable: true,
  72297. configurable: true
  72298. });
  72299. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72300. /**
  72301. * Fired when the thumbstick button on this controller is modified
  72302. */
  72303. get: function () {
  72304. return this.onPadStateChangedObservable;
  72305. },
  72306. enumerable: true,
  72307. configurable: true
  72308. });
  72309. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72310. /**
  72311. * Fired when the touchpad button on this controller is modified
  72312. */
  72313. get: function () {
  72314. return this.onTrackpadChangedObservable;
  72315. },
  72316. enumerable: true,
  72317. configurable: true
  72318. });
  72319. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72320. /**
  72321. * Fired when the touchpad values on this controller are modified
  72322. */
  72323. get: function () {
  72324. return this.onTrackpadValuesChangedObservable;
  72325. },
  72326. enumerable: true,
  72327. configurable: true
  72328. });
  72329. /**
  72330. * Called once per frame by the engine.
  72331. */
  72332. WindowsMotionController.prototype.update = function () {
  72333. _super.prototype.update.call(this);
  72334. if (this.browserGamepad.axes) {
  72335. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72336. this.trackpad.x = this.browserGamepad["axes"][2];
  72337. this.trackpad.y = this.browserGamepad["axes"][3];
  72338. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72339. }
  72340. // Only need to animate axes if there is a loaded mesh
  72341. if (this._loadedMeshInfo) {
  72342. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72343. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72344. }
  72345. }
  72346. }
  72347. };
  72348. /**
  72349. * Called once for each button that changed state since the last frame
  72350. * @param buttonIdx Which button index changed
  72351. * @param state New state of the button
  72352. * @param changes Which properties on the state changed since last frame
  72353. */
  72354. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72355. var buttonName = this._mapping.buttons[buttonIdx];
  72356. if (!buttonName) {
  72357. return;
  72358. }
  72359. // Only emit events for buttons that we know how to map from index to name
  72360. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72361. if (observable) {
  72362. observable.notifyObservers(state);
  72363. }
  72364. this._lerpButtonTransform(buttonName, state.value);
  72365. };
  72366. /**
  72367. * Moves the buttons on the controller mesh based on their current state
  72368. * @param buttonName the name of the button to move
  72369. * @param buttonValue the value of the button which determines the buttons new position
  72370. */
  72371. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72372. // If there is no loaded mesh, there is nothing to transform.
  72373. if (!this._loadedMeshInfo) {
  72374. return;
  72375. }
  72376. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72377. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72378. return;
  72379. }
  72380. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72381. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72382. };
  72383. /**
  72384. * Moves the axis on the controller mesh based on its current state
  72385. * @param axis the index of the axis
  72386. * @param axisValue the value of the axis which determines the meshes new position
  72387. * @hidden
  72388. */
  72389. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72390. if (!this._loadedMeshInfo) {
  72391. return;
  72392. }
  72393. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72394. if (!meshInfo) {
  72395. return;
  72396. }
  72397. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72398. return;
  72399. }
  72400. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72401. var lerpValue = axisValue * 0.5 + 0.5;
  72402. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72403. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72404. };
  72405. /**
  72406. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72407. * @param scene scene in which to add meshes
  72408. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72409. */
  72410. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72411. var _this = this;
  72412. if (forceDefault === void 0) { forceDefault = false; }
  72413. var path;
  72414. var filename;
  72415. // Checking if GLB loader is present
  72416. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72417. // Determine the device specific folder based on the ID suffix
  72418. var device = 'default';
  72419. if (this.id && !forceDefault) {
  72420. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72421. device = ((match && match[0]) || device);
  72422. }
  72423. // Hand
  72424. if (this.hand === 'left') {
  72425. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72426. }
  72427. else { // Right is the default if no hand is specified
  72428. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72429. }
  72430. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72431. }
  72432. else {
  72433. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72434. path = BABYLON.GenericController.MODEL_BASE_URL;
  72435. filename = BABYLON.GenericController.MODEL_FILENAME;
  72436. }
  72437. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72438. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72439. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72440. if (!_this._loadedMeshInfo) {
  72441. return;
  72442. }
  72443. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72444. _this.attachToMesh(_this._defaultModel);
  72445. if (meshLoaded) {
  72446. meshLoaded(_this._defaultModel);
  72447. }
  72448. }, null, function (scene, message) {
  72449. BABYLON.Tools.Log(message);
  72450. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72451. if (!forceDefault) {
  72452. _this.initControllerMesh(scene, meshLoaded, true);
  72453. }
  72454. });
  72455. };
  72456. /**
  72457. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72458. * can be transformed by button presses and axes values, based on this._mapping.
  72459. *
  72460. * @param scene scene in which the meshes exist
  72461. * @param meshes list of meshes that make up the controller model to process
  72462. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72463. */
  72464. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72465. var loadedMeshInfo = null;
  72466. // Create a new mesh to contain the glTF hierarchy
  72467. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72468. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72469. var childMesh = null;
  72470. for (var i = 0; i < meshes.length; i++) {
  72471. var mesh = meshes[i];
  72472. if (!mesh.parent) {
  72473. // Exclude controller meshes from picking results
  72474. mesh.isPickable = false;
  72475. // Handle root node, attach to the new parentMesh
  72476. childMesh = mesh;
  72477. break;
  72478. }
  72479. }
  72480. if (childMesh) {
  72481. childMesh.setParent(parentMesh);
  72482. // Create our mesh info. Note that this method will always return non-null.
  72483. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72484. }
  72485. else {
  72486. BABYLON.Tools.Warn('Could not find root node in model file.');
  72487. }
  72488. return loadedMeshInfo;
  72489. };
  72490. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72491. var loadedMeshInfo = new LoadedMeshInfo();
  72492. var i;
  72493. loadedMeshInfo.rootNode = rootNode;
  72494. // Reset the caches
  72495. loadedMeshInfo.buttonMeshes = {};
  72496. loadedMeshInfo.axisMeshes = {};
  72497. // Button Meshes
  72498. for (i = 0; i < this._mapping.buttons.length; i++) {
  72499. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72500. if (!buttonMeshName) {
  72501. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72502. continue;
  72503. }
  72504. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72505. if (!buttonMesh) {
  72506. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72507. continue;
  72508. }
  72509. var buttonMeshInfo = {
  72510. index: i,
  72511. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72512. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72513. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72514. };
  72515. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72516. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72517. }
  72518. else {
  72519. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72520. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72521. '(VALUE: ' + !!buttonMeshInfo.value +
  72522. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72523. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72524. ')');
  72525. }
  72526. }
  72527. // Axis Meshes
  72528. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72529. var axisMeshName = this._mapping.axisMeshNames[i];
  72530. if (!axisMeshName) {
  72531. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72532. continue;
  72533. }
  72534. var axisMesh = getChildByName(rootNode, axisMeshName);
  72535. if (!axisMesh) {
  72536. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72537. continue;
  72538. }
  72539. var axisMeshInfo = {
  72540. index: i,
  72541. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72542. min: getImmediateChildByName(axisMesh, 'MIN'),
  72543. max: getImmediateChildByName(axisMesh, 'MAX')
  72544. };
  72545. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72546. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72547. }
  72548. else {
  72549. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72550. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72551. '(VALUE: ' + !!axisMeshInfo.value +
  72552. ', MIN: ' + !!axisMeshInfo.min +
  72553. ', MAX:' + !!axisMeshInfo.max +
  72554. ')');
  72555. }
  72556. }
  72557. // Pointing Ray
  72558. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72559. if (!loadedMeshInfo.pointingPoseNode) {
  72560. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72561. }
  72562. return loadedMeshInfo;
  72563. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72564. function getChildByName(node, name) {
  72565. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72566. }
  72567. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72568. function getImmediateChildByName(node, name) {
  72569. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72570. }
  72571. };
  72572. /**
  72573. * Gets the ray of the controller in the direction the controller is pointing
  72574. * @param length the length the resulting ray should be
  72575. * @returns a ray in the direction the controller is pointing
  72576. */
  72577. WindowsMotionController.prototype.getForwardRay = function (length) {
  72578. if (length === void 0) { length = 100; }
  72579. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72580. return _super.prototype.getForwardRay.call(this, length);
  72581. }
  72582. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72583. var origin = m.getTranslation();
  72584. var forward = new BABYLON.Vector3(0, 0, -1);
  72585. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72586. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72587. return new BABYLON.Ray(origin, direction, length);
  72588. };
  72589. /**
  72590. * Disposes of the controller
  72591. */
  72592. WindowsMotionController.prototype.dispose = function () {
  72593. _super.prototype.dispose.call(this);
  72594. this.onTrackpadChangedObservable.clear();
  72595. };
  72596. /**
  72597. * The base url used to load the left and right controller models
  72598. */
  72599. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72600. /**
  72601. * The name of the left controller model file
  72602. */
  72603. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72604. /**
  72605. * The name of the right controller model file
  72606. */
  72607. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72608. /**
  72609. * The controller name prefix for this controller type
  72610. */
  72611. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72612. /**
  72613. * The controller id pattern for this controller type
  72614. */
  72615. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72616. return WindowsMotionController;
  72617. }(BABYLON.WebVRController));
  72618. BABYLON.WindowsMotionController = WindowsMotionController;
  72619. })(BABYLON || (BABYLON = {}));
  72620. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72621. var BABYLON;
  72622. (function (BABYLON) {
  72623. /**
  72624. * Gear VR Controller
  72625. */
  72626. var GearVRController = /** @class */ (function (_super) {
  72627. __extends(GearVRController, _super);
  72628. /**
  72629. * Creates a new GearVRController from a gamepad
  72630. * @param vrGamepad the gamepad that the controller should be created from
  72631. */
  72632. function GearVRController(vrGamepad) {
  72633. var _this = _super.call(this, vrGamepad) || this;
  72634. _this._buttonIndexToObservableNameMap = [
  72635. 'onTrackpadChangedObservable',
  72636. 'onTriggerStateChangedObservable' // Trigger
  72637. ];
  72638. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72639. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72640. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72641. return _this;
  72642. }
  72643. /**
  72644. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72645. * @param scene scene in which to add meshes
  72646. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72647. */
  72648. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72649. var _this = this;
  72650. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72651. _this._defaultModel = newMeshes[1];
  72652. _this.attachToMesh(_this._defaultModel);
  72653. if (meshLoaded) {
  72654. meshLoaded(_this._defaultModel);
  72655. }
  72656. });
  72657. };
  72658. /**
  72659. * Called once for each button that changed state since the last frame
  72660. * @param buttonIdx Which button index changed
  72661. * @param state New state of the button
  72662. * @param changes Which properties on the state changed since last frame
  72663. */
  72664. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72665. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72666. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72667. // Only emit events for buttons that we know how to map from index to observable
  72668. var observable = this[observableName];
  72669. if (observable) {
  72670. observable.notifyObservers(state);
  72671. }
  72672. }
  72673. };
  72674. /**
  72675. * Base Url for the controller model.
  72676. */
  72677. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72678. /**
  72679. * File name for the controller model.
  72680. */
  72681. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72682. /**
  72683. * Gamepad Id prefix used to identify this controller.
  72684. */
  72685. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72686. return GearVRController;
  72687. }(BABYLON.WebVRController));
  72688. BABYLON.GearVRController = GearVRController;
  72689. })(BABYLON || (BABYLON = {}));
  72690. //# sourceMappingURL=babylon.gearVRController.js.map
  72691. var BABYLON;
  72692. (function (BABYLON) {
  72693. /**
  72694. * Google Daydream controller
  72695. */
  72696. var DaydreamController = /** @class */ (function (_super) {
  72697. __extends(DaydreamController, _super);
  72698. /**
  72699. * Creates a new DaydreamController from a gamepad
  72700. * @param vrGamepad the gamepad that the controller should be created from
  72701. */
  72702. function DaydreamController(vrGamepad) {
  72703. var _this = _super.call(this, vrGamepad) || this;
  72704. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72705. return _this;
  72706. }
  72707. /**
  72708. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72709. * @param scene scene in which to add meshes
  72710. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72711. */
  72712. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72713. var _this = this;
  72714. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72715. _this._defaultModel = newMeshes[1];
  72716. _this.attachToMesh(_this._defaultModel);
  72717. if (meshLoaded) {
  72718. meshLoaded(_this._defaultModel);
  72719. }
  72720. });
  72721. };
  72722. /**
  72723. * Called once for each button that changed state since the last frame
  72724. * @param buttonIdx Which button index changed
  72725. * @param state New state of the button
  72726. * @param changes Which properties on the state changed since last frame
  72727. */
  72728. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72729. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72730. if (buttonIdx === 0) {
  72731. var observable = this.onTriggerStateChangedObservable;
  72732. if (observable) {
  72733. observable.notifyObservers(state);
  72734. }
  72735. }
  72736. else {
  72737. // If the app or home buttons are ever made available
  72738. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72739. }
  72740. };
  72741. /**
  72742. * Base Url for the controller model.
  72743. */
  72744. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72745. /**
  72746. * File name for the controller model.
  72747. */
  72748. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72749. /**
  72750. * Gamepad Id prefix used to identify Daydream Controller.
  72751. */
  72752. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72753. return DaydreamController;
  72754. }(BABYLON.WebVRController));
  72755. BABYLON.DaydreamController = DaydreamController;
  72756. })(BABYLON || (BABYLON = {}));
  72757. //# sourceMappingURL=babylon.daydreamController.js.map
  72758. var BABYLON;
  72759. (function (BABYLON) {
  72760. var FollowCamera = /** @class */ (function (_super) {
  72761. __extends(FollowCamera, _super);
  72762. function FollowCamera(name, position, scene, lockedTarget) {
  72763. if (lockedTarget === void 0) { lockedTarget = null; }
  72764. var _this = _super.call(this, name, position, scene) || this;
  72765. _this.radius = 12;
  72766. _this.rotationOffset = 0;
  72767. _this.heightOffset = 4;
  72768. _this.cameraAcceleration = 0.05;
  72769. _this.maxCameraSpeed = 20;
  72770. _this.lockedTarget = lockedTarget;
  72771. return _this;
  72772. }
  72773. FollowCamera.prototype.getRadians = function (degrees) {
  72774. return degrees * Math.PI / 180;
  72775. };
  72776. FollowCamera.prototype.follow = function (cameraTarget) {
  72777. if (!cameraTarget)
  72778. return;
  72779. var yRotation;
  72780. if (cameraTarget.rotationQuaternion) {
  72781. var rotMatrix = new BABYLON.Matrix();
  72782. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72783. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72784. }
  72785. else {
  72786. yRotation = cameraTarget.rotation.y;
  72787. }
  72788. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72789. var targetPosition = cameraTarget.getAbsolutePosition();
  72790. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72791. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72792. var dx = targetX - this.position.x;
  72793. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72794. var dz = (targetZ) - this.position.z;
  72795. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72796. var vy = dy * this.cameraAcceleration;
  72797. var vz = dz * this.cameraAcceleration * 2;
  72798. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72799. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72800. }
  72801. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72802. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72803. }
  72804. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72805. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72806. }
  72807. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72808. this.setTarget(targetPosition);
  72809. };
  72810. FollowCamera.prototype._checkInputs = function () {
  72811. _super.prototype._checkInputs.call(this);
  72812. if (this.lockedTarget) {
  72813. this.follow(this.lockedTarget);
  72814. }
  72815. };
  72816. FollowCamera.prototype.getClassName = function () {
  72817. return "FollowCamera";
  72818. };
  72819. __decorate([
  72820. BABYLON.serialize()
  72821. ], FollowCamera.prototype, "radius", void 0);
  72822. __decorate([
  72823. BABYLON.serialize()
  72824. ], FollowCamera.prototype, "rotationOffset", void 0);
  72825. __decorate([
  72826. BABYLON.serialize()
  72827. ], FollowCamera.prototype, "heightOffset", void 0);
  72828. __decorate([
  72829. BABYLON.serialize()
  72830. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72831. __decorate([
  72832. BABYLON.serialize()
  72833. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72834. __decorate([
  72835. BABYLON.serializeAsMeshReference("lockedTargetId")
  72836. ], FollowCamera.prototype, "lockedTarget", void 0);
  72837. return FollowCamera;
  72838. }(BABYLON.TargetCamera));
  72839. BABYLON.FollowCamera = FollowCamera;
  72840. var ArcFollowCamera = /** @class */ (function (_super) {
  72841. __extends(ArcFollowCamera, _super);
  72842. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72843. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72844. _this.alpha = alpha;
  72845. _this.beta = beta;
  72846. _this.radius = radius;
  72847. _this.target = target;
  72848. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72849. _this.follow();
  72850. return _this;
  72851. }
  72852. ArcFollowCamera.prototype.follow = function () {
  72853. if (!this.target) {
  72854. return;
  72855. }
  72856. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72857. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72858. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72859. var targetPosition = this.target.getAbsolutePosition();
  72860. this.position = targetPosition.add(this._cartesianCoordinates);
  72861. this.setTarget(targetPosition);
  72862. };
  72863. ArcFollowCamera.prototype._checkInputs = function () {
  72864. _super.prototype._checkInputs.call(this);
  72865. this.follow();
  72866. };
  72867. ArcFollowCamera.prototype.getClassName = function () {
  72868. return "ArcFollowCamera";
  72869. };
  72870. return ArcFollowCamera;
  72871. }(BABYLON.TargetCamera));
  72872. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72873. })(BABYLON || (BABYLON = {}));
  72874. //# sourceMappingURL=babylon.followCamera.js.map
  72875. var BABYLON;
  72876. (function (BABYLON) {
  72877. // We're mainly based on the logic defined into the FreeCamera code
  72878. var UniversalCamera = /** @class */ (function (_super) {
  72879. __extends(UniversalCamera, _super);
  72880. //-- end properties for backward compatibility for inputs
  72881. function UniversalCamera(name, position, scene) {
  72882. var _this = _super.call(this, name, position, scene) || this;
  72883. _this.inputs.addGamepad();
  72884. return _this;
  72885. }
  72886. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72887. //-- Begin properties for backward compatibility for inputs
  72888. get: function () {
  72889. var gamepad = this.inputs.attached["gamepad"];
  72890. if (gamepad)
  72891. return gamepad.gamepadAngularSensibility;
  72892. return 0;
  72893. },
  72894. set: function (value) {
  72895. var gamepad = this.inputs.attached["gamepad"];
  72896. if (gamepad)
  72897. gamepad.gamepadAngularSensibility = value;
  72898. },
  72899. enumerable: true,
  72900. configurable: true
  72901. });
  72902. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72903. get: function () {
  72904. var gamepad = this.inputs.attached["gamepad"];
  72905. if (gamepad)
  72906. return gamepad.gamepadMoveSensibility;
  72907. return 0;
  72908. },
  72909. set: function (value) {
  72910. var gamepad = this.inputs.attached["gamepad"];
  72911. if (gamepad)
  72912. gamepad.gamepadMoveSensibility = value;
  72913. },
  72914. enumerable: true,
  72915. configurable: true
  72916. });
  72917. UniversalCamera.prototype.getClassName = function () {
  72918. return "UniversalCamera";
  72919. };
  72920. return UniversalCamera;
  72921. }(BABYLON.TouchCamera));
  72922. BABYLON.UniversalCamera = UniversalCamera;
  72923. })(BABYLON || (BABYLON = {}));
  72924. //# sourceMappingURL=babylon.universalCamera.js.map
  72925. var BABYLON;
  72926. (function (BABYLON) {
  72927. // We're mainly based on the logic defined into the FreeCamera code
  72928. var GamepadCamera = /** @class */ (function (_super) {
  72929. __extends(GamepadCamera, _super);
  72930. //-- end properties for backward compatibility for inputs
  72931. function GamepadCamera(name, position, scene) {
  72932. return _super.call(this, name, position, scene) || this;
  72933. }
  72934. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72935. //-- Begin properties for backward compatibility for inputs
  72936. get: function () {
  72937. var gamepad = this.inputs.attached["gamepad"];
  72938. if (gamepad)
  72939. return gamepad.gamepadAngularSensibility;
  72940. return 0;
  72941. },
  72942. set: function (value) {
  72943. var gamepad = this.inputs.attached["gamepad"];
  72944. if (gamepad)
  72945. gamepad.gamepadAngularSensibility = value;
  72946. },
  72947. enumerable: true,
  72948. configurable: true
  72949. });
  72950. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72951. get: function () {
  72952. var gamepad = this.inputs.attached["gamepad"];
  72953. if (gamepad)
  72954. return gamepad.gamepadMoveSensibility;
  72955. return 0;
  72956. },
  72957. set: function (value) {
  72958. var gamepad = this.inputs.attached["gamepad"];
  72959. if (gamepad)
  72960. gamepad.gamepadMoveSensibility = value;
  72961. },
  72962. enumerable: true,
  72963. configurable: true
  72964. });
  72965. GamepadCamera.prototype.getClassName = function () {
  72966. return "GamepadCamera";
  72967. };
  72968. return GamepadCamera;
  72969. }(BABYLON.UniversalCamera));
  72970. BABYLON.GamepadCamera = GamepadCamera;
  72971. })(BABYLON || (BABYLON = {}));
  72972. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72973. var BABYLON;
  72974. (function (BABYLON) {
  72975. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72976. function PostProcessRenderPipelineManager() {
  72977. this._renderPipelines = {};
  72978. }
  72979. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72980. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72981. };
  72982. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72983. if (unique === void 0) { unique = false; }
  72984. var renderPipeline = this._renderPipelines[renderPipelineName];
  72985. if (!renderPipeline) {
  72986. return;
  72987. }
  72988. renderPipeline._attachCameras(cameras, unique);
  72989. };
  72990. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72991. var renderPipeline = this._renderPipelines[renderPipelineName];
  72992. if (!renderPipeline) {
  72993. return;
  72994. }
  72995. renderPipeline._detachCameras(cameras);
  72996. };
  72997. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72998. var renderPipeline = this._renderPipelines[renderPipelineName];
  72999. if (!renderPipeline) {
  73000. return;
  73001. }
  73002. renderPipeline._enableEffect(renderEffectName, cameras);
  73003. };
  73004. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73005. var renderPipeline = this._renderPipelines[renderPipelineName];
  73006. if (!renderPipeline) {
  73007. return;
  73008. }
  73009. renderPipeline._disableEffect(renderEffectName, cameras);
  73010. };
  73011. PostProcessRenderPipelineManager.prototype.update = function () {
  73012. for (var renderPipelineName in this._renderPipelines) {
  73013. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73014. var pipeline = this._renderPipelines[renderPipelineName];
  73015. if (!pipeline.isSupported) {
  73016. pipeline.dispose();
  73017. delete this._renderPipelines[renderPipelineName];
  73018. }
  73019. else {
  73020. pipeline._update();
  73021. }
  73022. }
  73023. }
  73024. };
  73025. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73026. for (var renderPipelineName in this._renderPipelines) {
  73027. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73028. var pipeline = this._renderPipelines[renderPipelineName];
  73029. pipeline._rebuild();
  73030. }
  73031. }
  73032. };
  73033. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73034. for (var renderPipelineName in this._renderPipelines) {
  73035. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73036. var pipeline = this._renderPipelines[renderPipelineName];
  73037. pipeline.dispose();
  73038. }
  73039. }
  73040. };
  73041. return PostProcessRenderPipelineManager;
  73042. }());
  73043. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73044. })(BABYLON || (BABYLON = {}));
  73045. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73046. var BABYLON;
  73047. (function (BABYLON) {
  73048. /**
  73049. * This represents a set of one or more post processes in Babylon.
  73050. * A post process can be used to apply a shader to a texture after it is rendered.
  73051. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73052. */
  73053. var PostProcessRenderEffect = /** @class */ (function () {
  73054. /**
  73055. * Instantiates a post process render effect.
  73056. * A post process can be used to apply a shader to a texture after it is rendered.
  73057. * @param engine The engine the effect is tied to
  73058. * @param name The name of the effect
  73059. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73060. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73061. */
  73062. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73063. this._name = name;
  73064. this._singleInstance = singleInstance || true;
  73065. this._getPostProcesses = getPostProcesses;
  73066. this._cameras = {};
  73067. this._indicesForCamera = {};
  73068. this._postProcesses = {};
  73069. }
  73070. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73071. /**
  73072. * Checks if all the post processes in the effect are supported.
  73073. */
  73074. get: function () {
  73075. for (var index in this._postProcesses) {
  73076. if (this._postProcesses.hasOwnProperty(index)) {
  73077. var pps = this._postProcesses[index];
  73078. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73079. if (!pps[ppIndex].isSupported) {
  73080. return false;
  73081. }
  73082. }
  73083. }
  73084. }
  73085. return true;
  73086. },
  73087. enumerable: true,
  73088. configurable: true
  73089. });
  73090. /**
  73091. * Updates the current state of the effect
  73092. */
  73093. PostProcessRenderEffect.prototype._update = function () {
  73094. };
  73095. /**
  73096. * Attaches the effect on cameras
  73097. * @param cameras The camera to attach to.
  73098. */
  73099. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73100. var _this = this;
  73101. var cameraKey;
  73102. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73103. if (!cams) {
  73104. return;
  73105. }
  73106. for (var i = 0; i < cams.length; i++) {
  73107. var camera = cams[i];
  73108. var cameraName = camera.name;
  73109. if (this._singleInstance) {
  73110. cameraKey = 0;
  73111. }
  73112. else {
  73113. cameraKey = cameraName;
  73114. }
  73115. if (!this._postProcesses[cameraKey]) {
  73116. var postProcess = this._getPostProcesses();
  73117. if (postProcess) {
  73118. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73119. }
  73120. }
  73121. if (!this._indicesForCamera[cameraName]) {
  73122. this._indicesForCamera[cameraName] = [];
  73123. }
  73124. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73125. var index = camera.attachPostProcess(postProcess);
  73126. _this._indicesForCamera[cameraName].push(index);
  73127. });
  73128. if (!this._cameras[cameraName]) {
  73129. this._cameras[cameraName] = camera;
  73130. }
  73131. }
  73132. };
  73133. /**
  73134. * Detatches the effect on cameras
  73135. * @param cameras The camera to detatch from.
  73136. */
  73137. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73138. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73139. if (!cams) {
  73140. return;
  73141. }
  73142. for (var i = 0; i < cams.length; i++) {
  73143. var camera = cams[i];
  73144. var cameraName = camera.name;
  73145. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73146. camera.detachPostProcess(postProcess);
  73147. });
  73148. if (this._cameras[cameraName]) {
  73149. //this._indicesForCamera.splice(index, 1);
  73150. this._cameras[cameraName] = null;
  73151. }
  73152. }
  73153. };
  73154. /**
  73155. * Enables the effect on given cameras
  73156. * @param cameras The camera to enable.
  73157. */
  73158. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73159. var _this = this;
  73160. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73161. if (!cams) {
  73162. return;
  73163. }
  73164. for (var i = 0; i < cams.length; i++) {
  73165. var camera = cams[i];
  73166. var cameraName = camera.name;
  73167. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73168. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73169. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73170. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73171. });
  73172. }
  73173. }
  73174. }
  73175. };
  73176. /**
  73177. * Disables the effect on the given cameras
  73178. * @param cameras The camera to disable.
  73179. */
  73180. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73181. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73182. if (!cams) {
  73183. return;
  73184. }
  73185. for (var i = 0; i < cams.length; i++) {
  73186. var camera = cams[i];
  73187. var cameraName = camera.name;
  73188. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73189. camera.detachPostProcess(postProcess);
  73190. });
  73191. }
  73192. };
  73193. /**
  73194. * Gets a list of the post processes contained in the effect.
  73195. * @param camera The camera to get the post processes on.
  73196. * @returns The list of the post processes in the effect.
  73197. */
  73198. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73199. if (this._singleInstance) {
  73200. return this._postProcesses[0];
  73201. }
  73202. else {
  73203. if (!camera) {
  73204. return null;
  73205. }
  73206. return this._postProcesses[camera.name];
  73207. }
  73208. };
  73209. return PostProcessRenderEffect;
  73210. }());
  73211. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73212. })(BABYLON || (BABYLON = {}));
  73213. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73214. var BABYLON;
  73215. (function (BABYLON) {
  73216. var PostProcessRenderPipeline = /** @class */ (function () {
  73217. function PostProcessRenderPipeline(engine, name) {
  73218. this.engine = engine;
  73219. this._name = name;
  73220. this._renderEffects = {};
  73221. this._renderEffectsForIsolatedPass = new Array();
  73222. this._cameras = [];
  73223. }
  73224. PostProcessRenderPipeline.prototype.getClassName = function () {
  73225. return "PostProcessRenderPipeline";
  73226. };
  73227. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73228. get: function () {
  73229. for (var renderEffectName in this._renderEffects) {
  73230. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73231. if (!this._renderEffects[renderEffectName].isSupported) {
  73232. return false;
  73233. }
  73234. }
  73235. }
  73236. return true;
  73237. },
  73238. enumerable: true,
  73239. configurable: true
  73240. });
  73241. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73242. this._renderEffects[renderEffect._name] = renderEffect;
  73243. };
  73244. // private
  73245. PostProcessRenderPipeline.prototype._rebuild = function () {
  73246. };
  73247. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73248. var renderEffects = this._renderEffects[renderEffectName];
  73249. if (!renderEffects) {
  73250. return;
  73251. }
  73252. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73253. };
  73254. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73255. var renderEffects = this._renderEffects[renderEffectName];
  73256. if (!renderEffects) {
  73257. return;
  73258. }
  73259. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73260. };
  73261. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73262. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73263. if (!cams) {
  73264. return;
  73265. }
  73266. var indicesToDelete = [];
  73267. var i;
  73268. for (i = 0; i < cams.length; i++) {
  73269. var camera = cams[i];
  73270. var cameraName = camera.name;
  73271. if (this._cameras.indexOf(camera) === -1) {
  73272. this._cameras[cameraName] = camera;
  73273. }
  73274. else if (unique) {
  73275. indicesToDelete.push(i);
  73276. }
  73277. }
  73278. for (i = 0; i < indicesToDelete.length; i++) {
  73279. cameras.splice(indicesToDelete[i], 1);
  73280. }
  73281. for (var renderEffectName in this._renderEffects) {
  73282. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73283. this._renderEffects[renderEffectName]._attachCameras(cams);
  73284. }
  73285. }
  73286. };
  73287. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73288. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73289. if (!cams) {
  73290. return;
  73291. }
  73292. for (var renderEffectName in this._renderEffects) {
  73293. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73294. this._renderEffects[renderEffectName]._detachCameras(cams);
  73295. }
  73296. }
  73297. for (var i = 0; i < cams.length; i++) {
  73298. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73299. }
  73300. };
  73301. PostProcessRenderPipeline.prototype._update = function () {
  73302. for (var renderEffectName in this._renderEffects) {
  73303. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73304. this._renderEffects[renderEffectName]._update();
  73305. }
  73306. }
  73307. for (var i = 0; i < this._cameras.length; i++) {
  73308. var cameraName = this._cameras[i].name;
  73309. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73310. this._renderEffectsForIsolatedPass[cameraName]._update();
  73311. }
  73312. }
  73313. };
  73314. PostProcessRenderPipeline.prototype._reset = function () {
  73315. this._renderEffects = {};
  73316. this._renderEffectsForIsolatedPass = new Array();
  73317. };
  73318. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73319. // 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)
  73320. var effectKeys = Object.keys(this._renderEffects);
  73321. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73322. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73323. if (postProcesses) {
  73324. postProcesses[0].samples = sampleCount;
  73325. return true;
  73326. }
  73327. }
  73328. return false;
  73329. };
  73330. PostProcessRenderPipeline.prototype.dispose = function () {
  73331. // Must be implemented by children
  73332. };
  73333. __decorate([
  73334. BABYLON.serialize()
  73335. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73336. return PostProcessRenderPipeline;
  73337. }());
  73338. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73339. })(BABYLON || (BABYLON = {}));
  73340. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73341. var BABYLON;
  73342. (function (BABYLON) {
  73343. /**
  73344. * This represents a depth renderer in Babylon.
  73345. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73346. */
  73347. var DepthRenderer = /** @class */ (function () {
  73348. /**
  73349. * Instantiates a depth renderer
  73350. * @param scene The scene the renderer belongs to
  73351. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73352. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73353. */
  73354. function DepthRenderer(scene, type, camera) {
  73355. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73356. if (camera === void 0) { camera = null; }
  73357. var _this = this;
  73358. this._scene = scene;
  73359. this._camera = camera;
  73360. var engine = scene.getEngine();
  73361. // Render target
  73362. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73363. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73364. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73365. this._depthMap.refreshRate = 1;
  73366. this._depthMap.renderParticles = false;
  73367. this._depthMap.renderList = null;
  73368. // Camera to get depth map from to support multiple concurrent cameras
  73369. this._depthMap.activeCamera = this._camera;
  73370. this._depthMap.ignoreCameraViewport = true;
  73371. this._depthMap.useCameraPostProcesses = false;
  73372. // set default depth value to 1.0 (far away)
  73373. this._depthMap.onClearObservable.add(function (engine) {
  73374. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73375. });
  73376. // Custom render function
  73377. var renderSubMesh = function (subMesh) {
  73378. var mesh = subMesh.getRenderingMesh();
  73379. var scene = _this._scene;
  73380. var engine = scene.getEngine();
  73381. var material = subMesh.getMaterial();
  73382. if (!material) {
  73383. return;
  73384. }
  73385. // Culling and reverse (right handed system)
  73386. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73387. // Managing instances
  73388. var batch = mesh._getInstancesRenderList(subMesh._id);
  73389. if (batch.mustReturn) {
  73390. return;
  73391. }
  73392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73393. var camera = _this._camera || scene.activeCamera;
  73394. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73395. engine.enableEffect(_this._effect);
  73396. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73397. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73398. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73399. // Alpha test
  73400. if (material && material.needAlphaTesting()) {
  73401. var alphaTexture = material.getAlphaTestTexture();
  73402. if (alphaTexture) {
  73403. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73404. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73405. }
  73406. }
  73407. // Bones
  73408. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73409. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73410. }
  73411. // Draw
  73412. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73413. }
  73414. };
  73415. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73416. var index;
  73417. if (depthOnlySubMeshes.length) {
  73418. engine.setColorWrite(false);
  73419. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73420. renderSubMesh(depthOnlySubMeshes.data[index]);
  73421. }
  73422. engine.setColorWrite(true);
  73423. }
  73424. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73425. renderSubMesh(opaqueSubMeshes.data[index]);
  73426. }
  73427. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73428. renderSubMesh(alphaTestSubMeshes.data[index]);
  73429. }
  73430. };
  73431. }
  73432. /**
  73433. * Creates the depth rendering effect and checks if the effect is ready.
  73434. * @param subMesh The submesh to be used to render the depth map of
  73435. * @param useInstances If multiple world instances should be used
  73436. * @returns if the depth renderer is ready to render the depth map
  73437. */
  73438. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73439. var material = subMesh.getMaterial();
  73440. if (material.disableDepthWrite) {
  73441. return false;
  73442. }
  73443. var defines = [];
  73444. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73445. var mesh = subMesh.getMesh();
  73446. // Alpha test
  73447. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73448. defines.push("#define ALPHATEST");
  73449. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73450. attribs.push(BABYLON.VertexBuffer.UVKind);
  73451. defines.push("#define UV1");
  73452. }
  73453. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73454. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73455. defines.push("#define UV2");
  73456. }
  73457. }
  73458. // Bones
  73459. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73462. if (mesh.numBoneInfluencers > 4) {
  73463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73465. }
  73466. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73467. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73468. }
  73469. else {
  73470. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73471. }
  73472. // Instances
  73473. if (useInstances) {
  73474. defines.push("#define INSTANCES");
  73475. attribs.push("world0");
  73476. attribs.push("world1");
  73477. attribs.push("world2");
  73478. attribs.push("world3");
  73479. }
  73480. // Get correct effect
  73481. var join = defines.join("\n");
  73482. if (this._cachedDefines !== join) {
  73483. this._cachedDefines = join;
  73484. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73485. }
  73486. return this._effect.isReady();
  73487. };
  73488. /**
  73489. * Gets the texture which the depth map will be written to.
  73490. * @returns The depth map texture
  73491. */
  73492. DepthRenderer.prototype.getDepthMap = function () {
  73493. return this._depthMap;
  73494. };
  73495. /**
  73496. * Disposes of the depth renderer.
  73497. */
  73498. DepthRenderer.prototype.dispose = function () {
  73499. this._depthMap.dispose();
  73500. };
  73501. return DepthRenderer;
  73502. }());
  73503. BABYLON.DepthRenderer = DepthRenderer;
  73504. })(BABYLON || (BABYLON = {}));
  73505. //# sourceMappingURL=babylon.depthRenderer.js.map
  73506. var BABYLON;
  73507. (function (BABYLON) {
  73508. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73509. __extends(SSAORenderingPipeline, _super);
  73510. /**
  73511. * @constructor
  73512. * @param {string} name - The rendering pipeline name
  73513. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73514. * @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 }
  73515. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73516. */
  73517. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73518. var _this = _super.call(this, scene.getEngine(), name) || this;
  73519. // Members
  73520. /**
  73521. * The PassPostProcess id in the pipeline that contains the original scene color
  73522. */
  73523. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73524. /**
  73525. * The SSAO PostProcess id in the pipeline
  73526. */
  73527. _this.SSAORenderEffect = "SSAORenderEffect";
  73528. /**
  73529. * The horizontal blur PostProcess id in the pipeline
  73530. */
  73531. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73532. /**
  73533. * The vertical blur PostProcess id in the pipeline
  73534. */
  73535. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73536. /**
  73537. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73538. */
  73539. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73540. /**
  73541. * The output strength of the SSAO post-process. Default value is 1.0.
  73542. */
  73543. _this.totalStrength = 1.0;
  73544. /**
  73545. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73546. */
  73547. _this.radius = 0.0001;
  73548. /**
  73549. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73550. * Must not be equal to fallOff and superior to fallOff.
  73551. * Default value is 0.975
  73552. */
  73553. _this.area = 0.0075;
  73554. /**
  73555. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73556. * Must not be equal to area and inferior to area.
  73557. * Default value is 0.0
  73558. */
  73559. _this.fallOff = 0.000001;
  73560. /**
  73561. * The base color of the SSAO post-process
  73562. * The final result is "base + ssao" between [0, 1]
  73563. */
  73564. _this.base = 0.5;
  73565. _this._firstUpdate = true;
  73566. _this._scene = scene;
  73567. // Set up assets
  73568. _this._createRandomTexture();
  73569. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73570. var ssaoRatio = ratio.ssaoRatio || ratio;
  73571. var combineRatio = ratio.combineRatio || ratio;
  73572. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73573. _this._createSSAOPostProcess(ssaoRatio);
  73574. _this._createBlurPostProcess(ssaoRatio);
  73575. _this._createSSAOCombinePostProcess(combineRatio);
  73576. // Set up pipeline
  73577. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73578. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73579. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73580. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73581. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73582. // Finish
  73583. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73584. if (cameras)
  73585. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73586. return _this;
  73587. }
  73588. // Public Methods
  73589. /**
  73590. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73591. */
  73592. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73593. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73594. for (var i = 0; i < this._scene.cameras.length; i++) {
  73595. var camera = this._scene.cameras[i];
  73596. this._originalColorPostProcess.dispose(camera);
  73597. this._ssaoPostProcess.dispose(camera);
  73598. this._blurHPostProcess.dispose(camera);
  73599. this._blurVPostProcess.dispose(camera);
  73600. this._ssaoCombinePostProcess.dispose(camera);
  73601. }
  73602. this._randomTexture.dispose();
  73603. if (disableDepthRender)
  73604. this._scene.disableDepthRenderer();
  73605. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73606. _super.prototype.dispose.call(this);
  73607. };
  73608. // Private Methods
  73609. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73610. var _this = this;
  73611. var size = 16;
  73612. 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);
  73613. 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);
  73614. this._blurHPostProcess.onActivateObservable.add(function () {
  73615. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73616. _this._blurHPostProcess.kernel = size * dw;
  73617. });
  73618. this._blurVPostProcess.onActivateObservable.add(function () {
  73619. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73620. _this._blurVPostProcess.kernel = size * dw;
  73621. });
  73622. };
  73623. SSAORenderingPipeline.prototype._rebuild = function () {
  73624. this._firstUpdate = true;
  73625. _super.prototype._rebuild.call(this);
  73626. };
  73627. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73628. var _this = this;
  73629. var numSamples = 16;
  73630. var sampleSphere = [
  73631. 0.5381, 0.1856, -0.4319,
  73632. 0.1379, 0.2486, 0.4430,
  73633. 0.3371, 0.5679, -0.0057,
  73634. -0.6999, -0.0451, -0.0019,
  73635. 0.0689, -0.1598, -0.8547,
  73636. 0.0560, 0.0069, -0.1843,
  73637. -0.0146, 0.1402, 0.0762,
  73638. 0.0100, -0.1924, -0.0344,
  73639. -0.3577, -0.5301, -0.4358,
  73640. -0.3169, 0.1063, 0.0158,
  73641. 0.0103, -0.5869, 0.0046,
  73642. -0.0897, -0.4940, 0.3287,
  73643. 0.7119, -0.0154, -0.0918,
  73644. -0.0533, 0.0596, -0.5411,
  73645. 0.0352, -0.0631, 0.5460,
  73646. -0.4776, 0.2847, -0.0271
  73647. ];
  73648. var samplesFactor = 1.0 / numSamples;
  73649. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73650. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73651. "area", "fallOff", "base", "range", "viewport"
  73652. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73653. this._ssaoPostProcess.onApply = function (effect) {
  73654. if (_this._firstUpdate) {
  73655. effect.setArray3("sampleSphere", sampleSphere);
  73656. effect.setFloat("samplesFactor", samplesFactor);
  73657. effect.setFloat("randTextureTiles", 4.0);
  73658. }
  73659. effect.setFloat("totalStrength", _this.totalStrength);
  73660. effect.setFloat("radius", _this.radius);
  73661. effect.setFloat("area", _this.area);
  73662. effect.setFloat("fallOff", _this.fallOff);
  73663. effect.setFloat("base", _this.base);
  73664. effect.setTexture("textureSampler", _this._depthTexture);
  73665. effect.setTexture("randomSampler", _this._randomTexture);
  73666. };
  73667. };
  73668. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73669. var _this = this;
  73670. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73671. this._ssaoCombinePostProcess.onApply = function (effect) {
  73672. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73673. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73674. };
  73675. };
  73676. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73677. var size = 512;
  73678. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73679. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73680. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73681. var context = this._randomTexture.getContext();
  73682. var rand = function (min, max) {
  73683. return Math.random() * (max - min) + min;
  73684. };
  73685. var randVector = BABYLON.Vector3.Zero();
  73686. for (var x = 0; x < size; x++) {
  73687. for (var y = 0; y < size; y++) {
  73688. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73689. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73690. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73691. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73692. context.fillRect(x, y, 1, 1);
  73693. }
  73694. }
  73695. this._randomTexture.update(false);
  73696. };
  73697. __decorate([
  73698. BABYLON.serialize()
  73699. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73700. __decorate([
  73701. BABYLON.serialize()
  73702. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73703. __decorate([
  73704. BABYLON.serialize()
  73705. ], SSAORenderingPipeline.prototype, "area", void 0);
  73706. __decorate([
  73707. BABYLON.serialize()
  73708. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73709. __decorate([
  73710. BABYLON.serialize()
  73711. ], SSAORenderingPipeline.prototype, "base", void 0);
  73712. return SSAORenderingPipeline;
  73713. }(BABYLON.PostProcessRenderPipeline));
  73714. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73715. })(BABYLON || (BABYLON = {}));
  73716. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73717. var BABYLON;
  73718. (function (BABYLON) {
  73719. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73720. __extends(SSAO2RenderingPipeline, _super);
  73721. /**
  73722. * @constructor
  73723. * @param {string} name - The rendering pipeline name
  73724. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73725. * @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 }
  73726. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73727. */
  73728. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73729. var _this = _super.call(this, scene.getEngine(), name) || this;
  73730. // Members
  73731. /**
  73732. * The PassPostProcess id in the pipeline that contains the original scene color
  73733. */
  73734. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73735. /**
  73736. * The SSAO PostProcess id in the pipeline
  73737. */
  73738. _this.SSAORenderEffect = "SSAORenderEffect";
  73739. /**
  73740. * The horizontal blur PostProcess id in the pipeline
  73741. */
  73742. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73743. /**
  73744. * The vertical blur PostProcess id in the pipeline
  73745. */
  73746. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73747. /**
  73748. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73749. */
  73750. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73751. /**
  73752. * The output strength of the SSAO post-process. Default value is 1.0.
  73753. */
  73754. _this.totalStrength = 1.0;
  73755. /**
  73756. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73757. */
  73758. _this.maxZ = 100.0;
  73759. /**
  73760. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73761. */
  73762. _this.minZAspect = 0.2;
  73763. /**
  73764. * Number of samples used for the SSAO calculations. Default value is 8
  73765. */
  73766. _this._samples = 8;
  73767. /**
  73768. * Are we using bilateral blur ?
  73769. */
  73770. _this._expensiveBlur = true;
  73771. /**
  73772. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73773. */
  73774. _this.radius = 2.0;
  73775. /**
  73776. * The base color of the SSAO post-process
  73777. * The final result is "base + ssao" between [0, 1]
  73778. */
  73779. _this.base = 0.1;
  73780. _this._firstUpdate = true;
  73781. _this._scene = scene;
  73782. _this._ratio = ratio;
  73783. if (!_this.isSupported) {
  73784. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73785. return _this;
  73786. }
  73787. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73788. var blurRatio = _this._ratio.blurRatio || ratio;
  73789. // Set up assets
  73790. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73791. _this._createRandomTexture();
  73792. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73793. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73794. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73795. _this._createSSAOPostProcess(1.0);
  73796. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73797. _this._createSSAOCombinePostProcess(blurRatio);
  73798. // Set up pipeline
  73799. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73800. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73801. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73802. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73803. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73804. // Finish
  73805. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73806. if (cameras)
  73807. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73808. return _this;
  73809. }
  73810. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73811. get: function () {
  73812. return this._samples;
  73813. },
  73814. set: function (n) {
  73815. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73816. this._samples = n;
  73817. this._sampleSphere = this._generateHemisphere();
  73818. this._firstUpdate = true;
  73819. },
  73820. enumerable: true,
  73821. configurable: true
  73822. });
  73823. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73824. get: function () {
  73825. return this._expensiveBlur;
  73826. },
  73827. set: function (b) {
  73828. 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"]);
  73829. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73830. this._expensiveBlur = b;
  73831. this._firstUpdate = true;
  73832. },
  73833. enumerable: true,
  73834. configurable: true
  73835. });
  73836. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73837. /**
  73838. * Support test.
  73839. */
  73840. get: function () {
  73841. var engine = BABYLON.Engine.LastCreatedEngine;
  73842. if (!engine) {
  73843. return false;
  73844. }
  73845. return engine.getCaps().drawBuffersExtension;
  73846. },
  73847. enumerable: true,
  73848. configurable: true
  73849. });
  73850. // Public Methods
  73851. /**
  73852. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73853. */
  73854. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73855. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73856. for (var i = 0; i < this._scene.cameras.length; i++) {
  73857. var camera = this._scene.cameras[i];
  73858. this._originalColorPostProcess.dispose(camera);
  73859. this._ssaoPostProcess.dispose(camera);
  73860. this._blurHPostProcess.dispose(camera);
  73861. this._blurVPostProcess.dispose(camera);
  73862. this._ssaoCombinePostProcess.dispose(camera);
  73863. }
  73864. this._randomTexture.dispose();
  73865. if (disableGeometryBufferRenderer)
  73866. this._scene.disableGeometryBufferRenderer();
  73867. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73868. _super.prototype.dispose.call(this);
  73869. };
  73870. // Private Methods
  73871. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73872. var _this = this;
  73873. this._samplerOffsets = [];
  73874. var expensive = this.expensiveBlur;
  73875. for (var i = -8; i < 8; i++) {
  73876. this._samplerOffsets.push(i * 2 + 0.5);
  73877. }
  73878. 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");
  73879. this._blurHPostProcess.onApply = function (effect) {
  73880. if (!_this._scene.activeCamera) {
  73881. return;
  73882. }
  73883. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73884. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73885. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73886. effect.setFloat("radius", _this.radius);
  73887. effect.setTexture("depthSampler", _this._depthTexture);
  73888. if (_this._firstUpdate) {
  73889. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73890. }
  73891. };
  73892. 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");
  73893. this._blurVPostProcess.onApply = function (effect) {
  73894. if (!_this._scene.activeCamera) {
  73895. return;
  73896. }
  73897. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73898. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73899. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73900. effect.setFloat("radius", _this.radius);
  73901. effect.setTexture("depthSampler", _this._depthTexture);
  73902. if (_this._firstUpdate) {
  73903. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73904. _this._firstUpdate = false;
  73905. }
  73906. };
  73907. };
  73908. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73909. this._firstUpdate = true;
  73910. _super.prototype._rebuild.call(this);
  73911. };
  73912. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73913. var numSamples = this.samples;
  73914. var result = [];
  73915. var vector, scale;
  73916. var rand = function (min, max) {
  73917. return Math.random() * (max - min) + min;
  73918. };
  73919. var i = 0;
  73920. while (i < numSamples) {
  73921. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73922. vector.normalize();
  73923. scale = i / numSamples;
  73924. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73925. vector.scaleInPlace(scale);
  73926. result.push(vector.x, vector.y, vector.z);
  73927. i++;
  73928. }
  73929. return result;
  73930. };
  73931. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73932. var _this = this;
  73933. var numSamples = this.samples;
  73934. this._sampleSphere = this._generateHemisphere();
  73935. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73936. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73937. "base", "range", "projection", "near", "far", "texelSize",
  73938. "xViewport", "yViewport", "maxZ", "minZAspect"
  73939. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73940. this._ssaoPostProcess.onApply = function (effect) {
  73941. if (_this._firstUpdate) {
  73942. effect.setArray3("sampleSphere", _this._sampleSphere);
  73943. effect.setFloat("randTextureTiles", 4.0);
  73944. }
  73945. if (!_this._scene.activeCamera) {
  73946. return;
  73947. }
  73948. effect.setFloat("samplesFactor", 1 / _this.samples);
  73949. effect.setFloat("totalStrength", _this.totalStrength);
  73950. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73951. effect.setFloat("radius", _this.radius);
  73952. effect.setFloat("maxZ", _this.maxZ);
  73953. effect.setFloat("minZAspect", _this.minZAspect);
  73954. effect.setFloat("base", _this.base);
  73955. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73956. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73957. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73958. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73959. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73960. effect.setTexture("textureSampler", _this._depthTexture);
  73961. effect.setTexture("normalSampler", _this._normalTexture);
  73962. effect.setTexture("randomSampler", _this._randomTexture);
  73963. };
  73964. };
  73965. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73966. var _this = this;
  73967. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73968. this._ssaoCombinePostProcess.onApply = function (effect) {
  73969. var viewport = _this._scene.activeCamera.viewport;
  73970. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73971. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73972. };
  73973. };
  73974. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73975. var size = 512;
  73976. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73977. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73978. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73979. var context = this._randomTexture.getContext();
  73980. var rand = function (min, max) {
  73981. return Math.random() * (max - min) + min;
  73982. };
  73983. var randVector = BABYLON.Vector3.Zero();
  73984. for (var x = 0; x < size; x++) {
  73985. for (var y = 0; y < size; y++) {
  73986. randVector.x = rand(0.0, 1.0);
  73987. randVector.y = rand(0.0, 1.0);
  73988. randVector.z = 0.0;
  73989. randVector.normalize();
  73990. randVector.scaleInPlace(255);
  73991. randVector.x = Math.floor(randVector.x);
  73992. randVector.y = Math.floor(randVector.y);
  73993. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73994. context.fillRect(x, y, 1, 1);
  73995. }
  73996. }
  73997. this._randomTexture.update(false);
  73998. };
  73999. /**
  74000. * Serialize the rendering pipeline (Used when exporting)
  74001. * @returns the serialized object
  74002. */
  74003. SSAO2RenderingPipeline.prototype.serialize = function () {
  74004. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74005. serializationObject.customType = "SSAO2RenderingPipeline";
  74006. return serializationObject;
  74007. };
  74008. /**
  74009. * Parse the serialized pipeline
  74010. * @param source Source pipeline.
  74011. * @param scene The scene to load the pipeline to.
  74012. * @param rootUrl The URL of the serialized pipeline.
  74013. * @returns An instantiated pipeline from the serialized object.
  74014. */
  74015. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74016. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74017. };
  74018. __decorate([
  74019. BABYLON.serialize()
  74020. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74021. __decorate([
  74022. BABYLON.serialize()
  74023. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74024. __decorate([
  74025. BABYLON.serialize()
  74026. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74027. __decorate([
  74028. BABYLON.serialize("samples")
  74029. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74030. __decorate([
  74031. BABYLON.serialize()
  74032. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74033. __decorate([
  74034. BABYLON.serialize("expensiveBlur")
  74035. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74036. __decorate([
  74037. BABYLON.serialize()
  74038. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74039. __decorate([
  74040. BABYLON.serialize()
  74041. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74042. return SSAO2RenderingPipeline;
  74043. }(BABYLON.PostProcessRenderPipeline));
  74044. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74045. })(BABYLON || (BABYLON = {}));
  74046. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74047. // BABYLON.JS Chromatic Aberration GLSL Shader
  74048. // Author: Olivier Guyot
  74049. // Separates very slightly R, G and B colors on the edges of the screen
  74050. // Inspired by Francois Tarlier & Martins Upitis
  74051. var BABYLON;
  74052. (function (BABYLON) {
  74053. var LensRenderingPipeline = /** @class */ (function (_super) {
  74054. __extends(LensRenderingPipeline, _super);
  74055. /**
  74056. * @constructor
  74057. *
  74058. * Effect parameters are as follow:
  74059. * {
  74060. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74061. * edge_blur: number; // from 0 to x (1 for realism)
  74062. * distortion: number; // from 0 to x (1 for realism)
  74063. * grain_amount: number; // from 0 to 1
  74064. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74065. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74066. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74067. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74068. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74069. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74070. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74071. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74072. * }
  74073. * Note: if an effect parameter is unset, effect is disabled
  74074. *
  74075. * @param {string} name - The rendering pipeline name
  74076. * @param {object} parameters - An object containing all parameters (see above)
  74077. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74078. * @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)
  74079. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74080. */
  74081. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74082. if (ratio === void 0) { ratio = 1.0; }
  74083. var _this = _super.call(this, scene.getEngine(), name) || this;
  74084. // Lens effects can be of the following:
  74085. // - chromatic aberration (slight shift of RGB colors)
  74086. // - blur on the edge of the lens
  74087. // - lens distortion
  74088. // - depth-of-field blur & highlights enhancing
  74089. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74090. // - grain effect (noise or custom texture)
  74091. // Two additional texture samplers are needed:
  74092. // - depth map (for depth-of-field)
  74093. // - grain texture
  74094. /**
  74095. * The chromatic aberration PostProcess id in the pipeline
  74096. */
  74097. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74098. /**
  74099. * The highlights enhancing PostProcess id in the pipeline
  74100. */
  74101. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74102. /**
  74103. * The depth-of-field PostProcess id in the pipeline
  74104. */
  74105. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74106. _this._scene = scene;
  74107. // Fetch texture samplers
  74108. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74109. if (parameters.grain_texture) {
  74110. _this._grainTexture = parameters.grain_texture;
  74111. }
  74112. else {
  74113. _this._createGrainTexture();
  74114. }
  74115. // save parameters
  74116. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74117. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74118. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74119. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74120. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74121. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74122. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74123. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74124. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74125. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74126. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74127. // Create effects
  74128. _this._createChromaticAberrationPostProcess(ratio);
  74129. _this._createHighlightsPostProcess(ratio);
  74130. _this._createDepthOfFieldPostProcess(ratio / 4);
  74131. // Set up pipeline
  74132. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74134. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74135. if (_this._highlightsGain === -1) {
  74136. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74137. }
  74138. // Finish
  74139. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74140. if (cameras) {
  74141. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74142. }
  74143. return _this;
  74144. }
  74145. // public methods (self explanatory)
  74146. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74147. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74148. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74149. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74150. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74151. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74152. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74153. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74154. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74155. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74156. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74157. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74158. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74159. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74160. };
  74161. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74162. this._highlightsPostProcess.updateEffect();
  74163. };
  74164. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74165. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74166. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74167. this._highlightsGain = amount;
  74168. };
  74169. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74170. if (this._highlightsGain === -1) {
  74171. this._highlightsGain = 1.0;
  74172. }
  74173. this._highlightsThreshold = amount;
  74174. };
  74175. LensRenderingPipeline.prototype.disableHighlights = function () {
  74176. this._highlightsGain = -1;
  74177. };
  74178. /**
  74179. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74180. */
  74181. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74182. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74183. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74184. this._chromaticAberrationPostProcess = null;
  74185. this._highlightsPostProcess = null;
  74186. this._depthOfFieldPostProcess = null;
  74187. this._grainTexture.dispose();
  74188. if (disableDepthRender)
  74189. this._scene.disableDepthRenderer();
  74190. };
  74191. // colors shifting and distortion
  74192. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74193. var _this = this;
  74194. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74195. [], // samplers
  74196. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74197. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74198. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74199. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74200. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74201. effect.setFloat('radialIntensity', 1);
  74202. effect.setFloat2('direction', 17, 17);
  74203. effect.setFloat2('centerPosition', 0.5, 0.5);
  74204. };
  74205. };
  74206. // highlights enhancing
  74207. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74208. var _this = this;
  74209. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74210. [], // samplers
  74211. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74212. this._highlightsPostProcess.onApply = function (effect) {
  74213. effect.setFloat('gain', _this._highlightsGain);
  74214. effect.setFloat('threshold', _this._highlightsThreshold);
  74215. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74216. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74217. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74218. };
  74219. };
  74220. // colors shifting and distortion
  74221. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74222. var _this = this;
  74223. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74224. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74225. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74226. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74227. this._depthOfFieldPostProcess.onApply = function (effect) {
  74228. effect.setTexture("depthSampler", _this._depthTexture);
  74229. effect.setTexture("grainSampler", _this._grainTexture);
  74230. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74231. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74232. effect.setFloat('grain_amount', _this._grainAmount);
  74233. effect.setBool('blur_noise', _this._blurNoise);
  74234. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74235. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74236. effect.setFloat('distortion', _this._distortion);
  74237. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74238. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74239. effect.setFloat('aperture', _this._dofAperture);
  74240. effect.setFloat('darken', _this._dofDarken);
  74241. effect.setFloat('edge_blur', _this._edgeBlur);
  74242. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74243. if (_this._scene.activeCamera) {
  74244. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74245. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74246. }
  74247. };
  74248. };
  74249. // creates a black and white random noise texture, 512x512
  74250. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74251. var size = 512;
  74252. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74253. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74254. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74255. var context = this._grainTexture.getContext();
  74256. var rand = function (min, max) {
  74257. return Math.random() * (max - min) + min;
  74258. };
  74259. var value;
  74260. for (var x = 0; x < size; x++) {
  74261. for (var y = 0; y < size; y++) {
  74262. value = Math.floor(rand(0.42, 0.58) * 255);
  74263. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74264. context.fillRect(x, y, 1, 1);
  74265. }
  74266. }
  74267. this._grainTexture.update(false);
  74268. };
  74269. return LensRenderingPipeline;
  74270. }(BABYLON.PostProcessRenderPipeline));
  74271. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74272. })(BABYLON || (BABYLON = {}));
  74273. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74274. var BABYLON;
  74275. (function (BABYLON) {
  74276. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74277. __extends(StandardRenderingPipeline, _super);
  74278. /**
  74279. * @constructor
  74280. * @param {string} name - The rendering pipeline name
  74281. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74282. * @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)
  74283. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74284. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74285. */
  74286. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74287. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74288. var _this = _super.call(this, scene.getEngine(), name) || this;
  74289. _this.downSampleX4PostProcess = null;
  74290. _this.brightPassPostProcess = null;
  74291. _this.blurHPostProcesses = [];
  74292. _this.blurVPostProcesses = [];
  74293. _this.textureAdderPostProcess = null;
  74294. _this.volumetricLightPostProcess = null;
  74295. _this.volumetricLightSmoothXPostProcess = null;
  74296. _this.volumetricLightSmoothYPostProcess = null;
  74297. _this.volumetricLightMergePostProces = null;
  74298. _this.volumetricLightFinalPostProcess = null;
  74299. _this.luminancePostProcess = null;
  74300. _this.luminanceDownSamplePostProcesses = [];
  74301. _this.hdrPostProcess = null;
  74302. _this.textureAdderFinalPostProcess = null;
  74303. _this.lensFlareFinalPostProcess = null;
  74304. _this.hdrFinalPostProcess = null;
  74305. _this.lensFlarePostProcess = null;
  74306. _this.lensFlareComposePostProcess = null;
  74307. _this.motionBlurPostProcess = null;
  74308. _this.depthOfFieldPostProcess = null;
  74309. // Values
  74310. _this.brightThreshold = 1.0;
  74311. _this.blurWidth = 512.0;
  74312. _this.horizontalBlur = false;
  74313. _this.exposure = 1.0;
  74314. _this.lensTexture = null;
  74315. _this.volumetricLightCoefficient = 0.2;
  74316. _this.volumetricLightPower = 4.0;
  74317. _this.volumetricLightBlurScale = 64.0;
  74318. _this.sourceLight = null;
  74319. _this.hdrMinimumLuminance = 1.0;
  74320. _this.hdrDecreaseRate = 0.5;
  74321. _this.hdrIncreaseRate = 0.5;
  74322. _this.lensColorTexture = null;
  74323. _this.lensFlareStrength = 20.0;
  74324. _this.lensFlareGhostDispersal = 1.4;
  74325. _this.lensFlareHaloWidth = 0.7;
  74326. _this.lensFlareDistortionStrength = 16.0;
  74327. _this.lensStarTexture = null;
  74328. _this.lensFlareDirtTexture = null;
  74329. _this.depthOfFieldDistance = 10.0;
  74330. _this.depthOfFieldBlurWidth = 64.0;
  74331. _this.motionStrength = 1.0;
  74332. // IAnimatable
  74333. _this.animations = [];
  74334. _this._currentDepthOfFieldSource = null;
  74335. _this._hdrCurrentLuminance = 1.0;
  74336. // Getters and setters
  74337. _this._bloomEnabled = true;
  74338. _this._depthOfFieldEnabled = false;
  74339. _this._vlsEnabled = false;
  74340. _this._lensFlareEnabled = false;
  74341. _this._hdrEnabled = false;
  74342. _this._motionBlurEnabled = false;
  74343. _this._motionBlurSamples = 64.0;
  74344. _this._volumetricLightStepsCount = 50.0;
  74345. _this._cameras = cameras || [];
  74346. // Initialize
  74347. _this._scene = scene;
  74348. _this._basePostProcess = originalPostProcess;
  74349. _this._ratio = ratio;
  74350. // Misc
  74351. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74352. // Finish
  74353. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74354. _this._buildPipeline();
  74355. return _this;
  74356. }
  74357. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74358. get: function () {
  74359. return this._bloomEnabled;
  74360. },
  74361. set: function (enabled) {
  74362. if (this._bloomEnabled === enabled) {
  74363. return;
  74364. }
  74365. this._bloomEnabled = enabled;
  74366. this._buildPipeline();
  74367. },
  74368. enumerable: true,
  74369. configurable: true
  74370. });
  74371. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74372. get: function () {
  74373. return this._depthOfFieldEnabled;
  74374. },
  74375. set: function (enabled) {
  74376. if (this._depthOfFieldEnabled === enabled) {
  74377. return;
  74378. }
  74379. this._depthOfFieldEnabled = enabled;
  74380. this._buildPipeline();
  74381. },
  74382. enumerable: true,
  74383. configurable: true
  74384. });
  74385. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74386. get: function () {
  74387. return this._lensFlareEnabled;
  74388. },
  74389. set: function (enabled) {
  74390. if (this._lensFlareEnabled === enabled) {
  74391. return;
  74392. }
  74393. this._lensFlareEnabled = enabled;
  74394. this._buildPipeline();
  74395. },
  74396. enumerable: true,
  74397. configurable: true
  74398. });
  74399. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74400. get: function () {
  74401. return this._hdrEnabled;
  74402. },
  74403. set: function (enabled) {
  74404. if (this._hdrEnabled === enabled) {
  74405. return;
  74406. }
  74407. this._hdrEnabled = enabled;
  74408. this._buildPipeline();
  74409. },
  74410. enumerable: true,
  74411. configurable: true
  74412. });
  74413. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74414. get: function () {
  74415. return this._vlsEnabled;
  74416. },
  74417. set: function (enabled) {
  74418. if (this._vlsEnabled === enabled) {
  74419. return;
  74420. }
  74421. if (enabled) {
  74422. var geometry = this._scene.enableGeometryBufferRenderer();
  74423. if (!geometry) {
  74424. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74425. return;
  74426. }
  74427. }
  74428. this._vlsEnabled = enabled;
  74429. this._buildPipeline();
  74430. },
  74431. enumerable: true,
  74432. configurable: true
  74433. });
  74434. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74435. get: function () {
  74436. return this._motionBlurEnabled;
  74437. },
  74438. set: function (enabled) {
  74439. if (this._motionBlurEnabled === enabled) {
  74440. return;
  74441. }
  74442. this._motionBlurEnabled = enabled;
  74443. this._buildPipeline();
  74444. },
  74445. enumerable: true,
  74446. configurable: true
  74447. });
  74448. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74449. get: function () {
  74450. return this._volumetricLightStepsCount;
  74451. },
  74452. set: function (count) {
  74453. if (this.volumetricLightPostProcess) {
  74454. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74455. }
  74456. this._volumetricLightStepsCount = count;
  74457. },
  74458. enumerable: true,
  74459. configurable: true
  74460. });
  74461. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74462. get: function () {
  74463. return this._motionBlurSamples;
  74464. },
  74465. set: function (samples) {
  74466. if (this.motionBlurPostProcess) {
  74467. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74468. }
  74469. this._motionBlurSamples = samples;
  74470. },
  74471. enumerable: true,
  74472. configurable: true
  74473. });
  74474. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74475. var _this = this;
  74476. var ratio = this._ratio;
  74477. var scene = this._scene;
  74478. this._disposePostProcesses();
  74479. this._reset();
  74480. // Create pass post-process
  74481. if (!this._basePostProcess) {
  74482. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74483. this.originalPostProcess.onApply = function (effect) {
  74484. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74485. };
  74486. }
  74487. else {
  74488. this.originalPostProcess = this._basePostProcess;
  74489. }
  74490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74491. this._currentDepthOfFieldSource = this.originalPostProcess;
  74492. if (this._bloomEnabled) {
  74493. // Create down sample X4 post-process
  74494. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74495. // Create bright pass post-process
  74496. this._createBrightPassPostProcess(scene, ratio / 2);
  74497. // Create gaussian blur post-processes (down sampling blurs)
  74498. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74499. // Create texture adder post-process
  74500. this._createTextureAdderPostProcess(scene, ratio);
  74501. // Create depth-of-field source post-process
  74502. 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);
  74503. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74504. }
  74505. if (this._vlsEnabled) {
  74506. // Create volumetric light
  74507. this._createVolumetricLightPostProcess(scene, ratio);
  74508. // Create volumetric light final post-process
  74509. 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);
  74510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74511. }
  74512. if (this._lensFlareEnabled) {
  74513. // Create lens flare post-process
  74514. this._createLensFlarePostProcess(scene, ratio);
  74515. // Create depth-of-field source post-process post lens-flare and disable it now
  74516. 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);
  74517. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74518. }
  74519. if (this._hdrEnabled) {
  74520. // Create luminance
  74521. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74522. // Create HDR
  74523. this._createHdrPostProcess(scene, ratio);
  74524. // Create depth-of-field source post-process post hdr and disable it now
  74525. 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);
  74526. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74527. }
  74528. if (this._depthOfFieldEnabled) {
  74529. // Create gaussian blur used by depth-of-field
  74530. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74531. // Create depth-of-field post-process
  74532. this._createDepthOfFieldPostProcess(scene, ratio);
  74533. }
  74534. if (this._motionBlurEnabled) {
  74535. // Create motion blur post-process
  74536. this._createMotionBlurPostProcess(scene, ratio);
  74537. }
  74538. if (this._cameras !== null) {
  74539. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74540. }
  74541. };
  74542. // Down Sample X4 Post-Processs
  74543. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74544. var _this = this;
  74545. var downSampleX4Offsets = new Array(32);
  74546. 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);
  74547. this.downSampleX4PostProcess.onApply = function (effect) {
  74548. var id = 0;
  74549. var width = _this.downSampleX4PostProcess.width;
  74550. var height = _this.downSampleX4PostProcess.height;
  74551. for (var i = -2; i < 2; i++) {
  74552. for (var j = -2; j < 2; j++) {
  74553. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74554. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74555. id += 2;
  74556. }
  74557. }
  74558. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74559. };
  74560. // Add to pipeline
  74561. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74562. };
  74563. // Brightpass Post-Process
  74564. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74565. var _this = this;
  74566. var brightOffsets = new Array(8);
  74567. 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);
  74568. this.brightPassPostProcess.onApply = function (effect) {
  74569. var sU = (1.0 / _this.brightPassPostProcess.width);
  74570. var sV = (1.0 / _this.brightPassPostProcess.height);
  74571. brightOffsets[0] = -0.5 * sU;
  74572. brightOffsets[1] = 0.5 * sV;
  74573. brightOffsets[2] = 0.5 * sU;
  74574. brightOffsets[3] = 0.5 * sV;
  74575. brightOffsets[4] = -0.5 * sU;
  74576. brightOffsets[5] = -0.5 * sV;
  74577. brightOffsets[6] = 0.5 * sU;
  74578. brightOffsets[7] = -0.5 * sV;
  74579. effect.setArray2("dsOffsets", brightOffsets);
  74580. effect.setFloat("brightThreshold", _this.brightThreshold);
  74581. };
  74582. // Add to pipeline
  74583. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74584. };
  74585. // Create blur H&V post-processes
  74586. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74587. var _this = this;
  74588. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74589. var engine = scene.getEngine();
  74590. 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);
  74591. 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);
  74592. blurX.onActivateObservable.add(function () {
  74593. var dw = blurX.width / engine.getRenderWidth();
  74594. blurX.kernel = _this[blurWidthKey] * dw;
  74595. });
  74596. blurY.onActivateObservable.add(function () {
  74597. var dw = blurY.height / engine.getRenderHeight();
  74598. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74599. });
  74600. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74601. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74602. this.blurHPostProcesses.push(blurX);
  74603. this.blurVPostProcesses.push(blurY);
  74604. };
  74605. // Create texture adder post-process
  74606. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74607. var _this = this;
  74608. 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);
  74609. this.textureAdderPostProcess.onApply = function (effect) {
  74610. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74611. effect.setTexture("lensSampler", _this.lensTexture);
  74612. effect.setFloat("exposure", _this.exposure);
  74613. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74614. };
  74615. // Add to pipeline
  74616. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74617. };
  74618. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74619. var _this = this;
  74620. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74621. geometryRenderer.enablePosition = true;
  74622. var geometry = geometryRenderer.getGBuffer();
  74623. // Base post-process
  74624. 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));
  74625. var depthValues = BABYLON.Vector2.Zero();
  74626. this.volumetricLightPostProcess.onApply = function (effect) {
  74627. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74628. var generator = _this.sourceLight.getShadowGenerator();
  74629. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74630. effect.setTexture("positionSampler", geometry.textures[2]);
  74631. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74632. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74633. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74634. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74635. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74636. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74637. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74638. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74639. effect.setVector2("depthValues", depthValues);
  74640. }
  74641. };
  74642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74643. // Smooth
  74644. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74645. // Merge
  74646. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74647. this.volumetricLightMergePostProces.onApply = function (effect) {
  74648. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74649. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74650. };
  74651. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74652. };
  74653. // Create luminance
  74654. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74655. var _this = this;
  74656. // Create luminance
  74657. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74658. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74659. var offsets = [];
  74660. this.luminancePostProcess.onApply = function (effect) {
  74661. var sU = (1.0 / _this.luminancePostProcess.width);
  74662. var sV = (1.0 / _this.luminancePostProcess.height);
  74663. offsets[0] = -0.5 * sU;
  74664. offsets[1] = 0.5 * sV;
  74665. offsets[2] = 0.5 * sU;
  74666. offsets[3] = 0.5 * sV;
  74667. offsets[4] = -0.5 * sU;
  74668. offsets[5] = -0.5 * sV;
  74669. offsets[6] = 0.5 * sU;
  74670. offsets[7] = -0.5 * sV;
  74671. effect.setArray2("lumOffsets", offsets);
  74672. };
  74673. // Add to pipeline
  74674. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74675. // Create down sample luminance
  74676. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74677. var size = Math.pow(3, i);
  74678. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74679. if (i === 0) {
  74680. defines += "#define FINAL_DOWN_SAMPLER";
  74681. }
  74682. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74683. this.luminanceDownSamplePostProcesses.push(postProcess);
  74684. }
  74685. // Create callbacks and add effects
  74686. var lastLuminance = this.luminancePostProcess;
  74687. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74688. var downSampleOffsets = new Array(18);
  74689. pp.onApply = function (effect) {
  74690. if (!lastLuminance) {
  74691. return;
  74692. }
  74693. var id = 0;
  74694. for (var x = -1; x < 2; x++) {
  74695. for (var y = -1; y < 2; y++) {
  74696. downSampleOffsets[id] = x / lastLuminance.width;
  74697. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74698. id += 2;
  74699. }
  74700. }
  74701. effect.setArray2("dsOffsets", downSampleOffsets);
  74702. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74703. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74704. lastLuminance = _this.luminancePostProcess;
  74705. }
  74706. else {
  74707. lastLuminance = pp;
  74708. }
  74709. };
  74710. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74711. pp.onAfterRender = function (effect) {
  74712. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74713. 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);
  74714. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74715. };
  74716. }
  74717. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74718. });
  74719. };
  74720. // Create HDR post-process
  74721. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74722. var _this = this;
  74723. 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);
  74724. var outputLiminance = 1;
  74725. var time = 0;
  74726. var lastTime = 0;
  74727. this.hdrPostProcess.onApply = function (effect) {
  74728. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74729. time += scene.getEngine().getDeltaTime();
  74730. if (outputLiminance < 0) {
  74731. outputLiminance = _this._hdrCurrentLuminance;
  74732. }
  74733. else {
  74734. var dt = (lastTime - time) / 1000.0;
  74735. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74736. outputLiminance += _this.hdrDecreaseRate * dt;
  74737. }
  74738. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74739. outputLiminance -= _this.hdrIncreaseRate * dt;
  74740. }
  74741. else {
  74742. outputLiminance = _this._hdrCurrentLuminance;
  74743. }
  74744. }
  74745. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74746. effect.setFloat("averageLuminance", outputLiminance);
  74747. lastTime = time;
  74748. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74749. };
  74750. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74751. };
  74752. // Create lens flare post-process
  74753. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74754. var _this = this;
  74755. 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);
  74756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74757. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74758. 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);
  74759. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74760. var resolution = new BABYLON.Vector2(0, 0);
  74761. // Lens flare
  74762. this.lensFlarePostProcess.onApply = function (effect) {
  74763. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74764. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74765. effect.setFloat("strength", _this.lensFlareStrength);
  74766. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74767. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74768. // Shift
  74769. resolution.x = _this.lensFlarePostProcess.width;
  74770. resolution.y = _this.lensFlarePostProcess.height;
  74771. effect.setVector2("resolution", resolution);
  74772. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74773. };
  74774. // Compose
  74775. 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);
  74776. 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);
  74777. this.lensFlareComposePostProcess.onApply = function (effect) {
  74778. if (!_this._scene.activeCamera) {
  74779. return;
  74780. }
  74781. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74782. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74783. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74784. // Lens start rotation matrix
  74785. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74786. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74787. 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));
  74788. camRot *= 4.0;
  74789. 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);
  74790. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74791. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74792. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74793. };
  74794. };
  74795. // Create depth-of-field post-process
  74796. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74797. var _this = this;
  74798. 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);
  74799. this.depthOfFieldPostProcess.onApply = function (effect) {
  74800. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74801. effect.setTexture("depthSampler", _this._getDepthTexture());
  74802. effect.setFloat("distance", _this.depthOfFieldDistance);
  74803. };
  74804. // Add to pipeline
  74805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74806. };
  74807. // Create motion blur post-process
  74808. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74809. var _this = this;
  74810. 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);
  74811. var motionScale = 0;
  74812. var prevViewProjection = BABYLON.Matrix.Identity();
  74813. var invViewProjection = BABYLON.Matrix.Identity();
  74814. var viewProjection = BABYLON.Matrix.Identity();
  74815. var screenSize = BABYLON.Vector2.Zero();
  74816. this.motionBlurPostProcess.onApply = function (effect) {
  74817. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74818. viewProjection.invertToRef(invViewProjection);
  74819. effect.setMatrix("inverseViewProjection", invViewProjection);
  74820. effect.setMatrix("prevViewProjection", prevViewProjection);
  74821. prevViewProjection = viewProjection;
  74822. screenSize.x = _this.motionBlurPostProcess.width;
  74823. screenSize.y = _this.motionBlurPostProcess.height;
  74824. effect.setVector2("screenSize", screenSize);
  74825. motionScale = scene.getEngine().getFps() / 60.0;
  74826. effect.setFloat("motionScale", motionScale);
  74827. effect.setFloat("motionStrength", _this.motionStrength);
  74828. effect.setTexture("depthSampler", _this._getDepthTexture());
  74829. };
  74830. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74831. };
  74832. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74833. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74834. var renderer = this._scene.enableGeometryBufferRenderer();
  74835. return renderer.getGBuffer().textures[0];
  74836. }
  74837. return this._scene.enableDepthRenderer().getDepthMap();
  74838. };
  74839. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74840. for (var i = 0; i < this._cameras.length; i++) {
  74841. var camera = this._cameras[i];
  74842. if (this.originalPostProcess) {
  74843. this.originalPostProcess.dispose(camera);
  74844. }
  74845. if (this.downSampleX4PostProcess) {
  74846. this.downSampleX4PostProcess.dispose(camera);
  74847. }
  74848. if (this.brightPassPostProcess) {
  74849. this.brightPassPostProcess.dispose(camera);
  74850. }
  74851. if (this.textureAdderPostProcess) {
  74852. this.textureAdderPostProcess.dispose(camera);
  74853. }
  74854. if (this.textureAdderFinalPostProcess) {
  74855. this.textureAdderFinalPostProcess.dispose(camera);
  74856. }
  74857. if (this.volumetricLightPostProcess) {
  74858. this.volumetricLightPostProcess.dispose(camera);
  74859. }
  74860. if (this.volumetricLightSmoothXPostProcess) {
  74861. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74862. }
  74863. if (this.volumetricLightSmoothYPostProcess) {
  74864. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74865. }
  74866. if (this.volumetricLightMergePostProces) {
  74867. this.volumetricLightMergePostProces.dispose(camera);
  74868. }
  74869. if (this.volumetricLightFinalPostProcess) {
  74870. this.volumetricLightFinalPostProcess.dispose(camera);
  74871. }
  74872. if (this.lensFlarePostProcess) {
  74873. this.lensFlarePostProcess.dispose(camera);
  74874. }
  74875. if (this.lensFlareComposePostProcess) {
  74876. this.lensFlareComposePostProcess.dispose(camera);
  74877. }
  74878. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74879. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74880. }
  74881. if (this.luminancePostProcess) {
  74882. this.luminancePostProcess.dispose(camera);
  74883. }
  74884. if (this.hdrPostProcess) {
  74885. this.hdrPostProcess.dispose(camera);
  74886. }
  74887. if (this.hdrFinalPostProcess) {
  74888. this.hdrFinalPostProcess.dispose(camera);
  74889. }
  74890. if (this.depthOfFieldPostProcess) {
  74891. this.depthOfFieldPostProcess.dispose(camera);
  74892. }
  74893. if (this.motionBlurPostProcess) {
  74894. this.motionBlurPostProcess.dispose(camera);
  74895. }
  74896. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74897. this.blurHPostProcesses[j].dispose(camera);
  74898. }
  74899. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74900. this.blurVPostProcesses[j].dispose(camera);
  74901. }
  74902. }
  74903. this.originalPostProcess = null;
  74904. this.downSampleX4PostProcess = null;
  74905. this.brightPassPostProcess = null;
  74906. this.textureAdderPostProcess = null;
  74907. this.textureAdderFinalPostProcess = null;
  74908. this.volumetricLightPostProcess = null;
  74909. this.volumetricLightSmoothXPostProcess = null;
  74910. this.volumetricLightSmoothYPostProcess = null;
  74911. this.volumetricLightMergePostProces = null;
  74912. this.volumetricLightFinalPostProcess = null;
  74913. this.lensFlarePostProcess = null;
  74914. this.lensFlareComposePostProcess = null;
  74915. this.luminancePostProcess = null;
  74916. this.hdrPostProcess = null;
  74917. this.hdrFinalPostProcess = null;
  74918. this.depthOfFieldPostProcess = null;
  74919. this.motionBlurPostProcess = null;
  74920. this.luminanceDownSamplePostProcesses = [];
  74921. this.blurHPostProcesses = [];
  74922. this.blurVPostProcesses = [];
  74923. };
  74924. /**
  74925. * Dispose of the pipeline and stop all post processes
  74926. */
  74927. StandardRenderingPipeline.prototype.dispose = function () {
  74928. this._disposePostProcesses();
  74929. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74930. _super.prototype.dispose.call(this);
  74931. };
  74932. /**
  74933. * Serialize the rendering pipeline (Used when exporting)
  74934. * @returns the serialized object
  74935. */
  74936. StandardRenderingPipeline.prototype.serialize = function () {
  74937. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74938. if (this.sourceLight) {
  74939. serializationObject.sourceLightId = this.sourceLight.id;
  74940. }
  74941. serializationObject.customType = "StandardRenderingPipeline";
  74942. return serializationObject;
  74943. };
  74944. /**
  74945. * Parse the serialized pipeline
  74946. * @param source Source pipeline.
  74947. * @param scene The scene to load the pipeline to.
  74948. * @param rootUrl The URL of the serialized pipeline.
  74949. * @returns An instantiated pipeline from the serialized object.
  74950. */
  74951. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74952. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74953. if (source.sourceLightId) {
  74954. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74955. }
  74956. return p;
  74957. };
  74958. // Luminance steps
  74959. StandardRenderingPipeline.LuminanceSteps = 6;
  74960. __decorate([
  74961. BABYLON.serialize()
  74962. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74963. __decorate([
  74964. BABYLON.serialize()
  74965. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74966. __decorate([
  74967. BABYLON.serialize()
  74968. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74969. __decorate([
  74970. BABYLON.serialize()
  74971. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74972. __decorate([
  74973. BABYLON.serializeAsTexture("lensTexture")
  74974. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74975. __decorate([
  74976. BABYLON.serialize()
  74977. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74978. __decorate([
  74979. BABYLON.serialize()
  74980. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74981. __decorate([
  74982. BABYLON.serialize()
  74983. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74984. __decorate([
  74985. BABYLON.serialize()
  74986. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74987. __decorate([
  74988. BABYLON.serialize()
  74989. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74990. __decorate([
  74991. BABYLON.serialize()
  74992. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74993. __decorate([
  74994. BABYLON.serializeAsTexture("lensColorTexture")
  74995. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74996. __decorate([
  74997. BABYLON.serialize()
  74998. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74999. __decorate([
  75000. BABYLON.serialize()
  75001. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75002. __decorate([
  75003. BABYLON.serialize()
  75004. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75005. __decorate([
  75006. BABYLON.serialize()
  75007. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75008. __decorate([
  75009. BABYLON.serializeAsTexture("lensStarTexture")
  75010. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75011. __decorate([
  75012. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75013. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75014. __decorate([
  75015. BABYLON.serialize()
  75016. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75017. __decorate([
  75018. BABYLON.serialize()
  75019. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75020. __decorate([
  75021. BABYLON.serialize()
  75022. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75023. __decorate([
  75024. BABYLON.serialize()
  75025. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75026. __decorate([
  75027. BABYLON.serialize()
  75028. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75029. __decorate([
  75030. BABYLON.serialize()
  75031. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75032. __decorate([
  75033. BABYLON.serialize()
  75034. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75035. __decorate([
  75036. BABYLON.serialize()
  75037. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75038. __decorate([
  75039. BABYLON.serialize()
  75040. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75041. __decorate([
  75042. BABYLON.serialize()
  75043. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75044. __decorate([
  75045. BABYLON.serialize()
  75046. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75047. __decorate([
  75048. BABYLON.serialize()
  75049. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75050. return StandardRenderingPipeline;
  75051. }(BABYLON.PostProcessRenderPipeline));
  75052. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75053. })(BABYLON || (BABYLON = {}));
  75054. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75055. var BABYLON;
  75056. (function (BABYLON) {
  75057. var FxaaPostProcess = /** @class */ (function (_super) {
  75058. __extends(FxaaPostProcess, _super);
  75059. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75060. if (camera === void 0) { camera = null; }
  75061. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75062. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75063. var defines = _this._getDefines();
  75064. _this.updateEffect(defines);
  75065. _this.onApplyObservable.add(function (effect) {
  75066. var texelSize = _this.texelSize;
  75067. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75068. });
  75069. return _this;
  75070. }
  75071. FxaaPostProcess.prototype._getDefines = function () {
  75072. var engine = this.getEngine();
  75073. if (!engine) {
  75074. return null;
  75075. }
  75076. var glInfo = engine.getGlInfo();
  75077. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75078. return "#define MALI 1\n";
  75079. }
  75080. return null;
  75081. };
  75082. return FxaaPostProcess;
  75083. }(BABYLON.PostProcess));
  75084. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75085. })(BABYLON || (BABYLON = {}));
  75086. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75087. var BABYLON;
  75088. (function (BABYLON) {
  75089. /**
  75090. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75091. */
  75092. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75093. __extends(ChromaticAberrationPostProcess, _super);
  75094. /**
  75095. * Creates a new instance ChromaticAberrationPostProcess
  75096. * @param name The name of the effect.
  75097. * @param screenWidth The width of the screen to apply the effect on.
  75098. * @param screenHeight The height of the screen to apply the effect on.
  75099. * @param options The required width/height ratio to downsize to before computing the render pass.
  75100. * @param camera The camera to apply the render pass to.
  75101. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75102. * @param engine The engine which the post process will be applied. (default: current engine)
  75103. * @param reusable If the post process can be reused on the same frame. (default: false)
  75104. * @param textureType Type of textures used when performing the post process. (default: 0)
  75105. * @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)
  75106. */
  75107. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75108. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75109. if (blockCompilation === void 0) { blockCompilation = false; }
  75110. 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;
  75111. /**
  75112. * The amount of seperation of rgb channels (default: 30)
  75113. */
  75114. _this.aberrationAmount = 30;
  75115. /**
  75116. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75117. */
  75118. _this.radialIntensity = 0;
  75119. /**
  75120. * 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))
  75121. */
  75122. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75123. /**
  75124. * 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))
  75125. */
  75126. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75127. _this.onApplyObservable.add(function (effect) {
  75128. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75129. effect.setFloat('screen_width', screenWidth);
  75130. effect.setFloat('screen_height', screenHeight);
  75131. effect.setFloat('radialIntensity', _this.radialIntensity);
  75132. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75133. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75134. });
  75135. return _this;
  75136. }
  75137. return ChromaticAberrationPostProcess;
  75138. }(BABYLON.PostProcess));
  75139. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75140. })(BABYLON || (BABYLON = {}));
  75141. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75142. var BABYLON;
  75143. (function (BABYLON) {
  75144. /**
  75145. * The GrainPostProcess adds noise to the image at mid luminance levels
  75146. */
  75147. var GrainPostProcess = /** @class */ (function (_super) {
  75148. __extends(GrainPostProcess, _super);
  75149. /**
  75150. * Creates a new instance of @see GrainPostProcess
  75151. * @param name The name of the effect.
  75152. * @param options The required width/height ratio to downsize to before computing the render pass.
  75153. * @param camera The camera to apply the render pass to.
  75154. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75155. * @param engine The engine which the post process will be applied. (default: current engine)
  75156. * @param reusable If the post process can be reused on the same frame. (default: false)
  75157. * @param textureType Type of textures used when performing the post process. (default: 0)
  75158. * @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)
  75159. */
  75160. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75161. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75162. if (blockCompilation === void 0) { blockCompilation = false; }
  75163. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75164. /**
  75165. * The intensity of the grain added (default: 30)
  75166. */
  75167. _this.intensity = 30;
  75168. /**
  75169. * If the grain should be randomized on every frame
  75170. */
  75171. _this.animated = false;
  75172. _this.onApplyObservable.add(function (effect) {
  75173. effect.setFloat('intensity', _this.intensity);
  75174. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75175. });
  75176. return _this;
  75177. }
  75178. return GrainPostProcess;
  75179. }(BABYLON.PostProcess));
  75180. BABYLON.GrainPostProcess = GrainPostProcess;
  75181. })(BABYLON || (BABYLON = {}));
  75182. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75183. var BABYLON;
  75184. (function (BABYLON) {
  75185. /**
  75186. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75187. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75188. */
  75189. var SharpenPostProcess = /** @class */ (function (_super) {
  75190. __extends(SharpenPostProcess, _super);
  75191. /**
  75192. * Creates a new instance ConvolutionPostProcess
  75193. * @param name The name of the effect.
  75194. * @param options The required width/height ratio to downsize to before computing the render pass.
  75195. * @param camera The camera to apply the render pass to.
  75196. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75197. * @param engine The engine which the post process will be applied. (default: current engine)
  75198. * @param reusable If the post process can be reused on the same frame. (default: false)
  75199. * @param textureType Type of textures used when performing the post process. (default: 0)
  75200. * @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)
  75201. */
  75202. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75203. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75204. if (blockCompilation === void 0) { blockCompilation = false; }
  75205. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75206. /**
  75207. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75208. */
  75209. _this.colorAmount = 1.0;
  75210. /**
  75211. * How much sharpness should be applied (default: 0.3)
  75212. */
  75213. _this.edgeAmount = 0.3;
  75214. _this.onApply = function (effect) {
  75215. effect.setFloat2("screenSize", _this.width, _this.height);
  75216. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75217. };
  75218. return _this;
  75219. }
  75220. return SharpenPostProcess;
  75221. }(BABYLON.PostProcess));
  75222. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75223. })(BABYLON || (BABYLON = {}));
  75224. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75225. var BABYLON;
  75226. (function (BABYLON) {
  75227. /**
  75228. * The Blur Post Process which blurs an image based on a kernel and direction.
  75229. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75230. */
  75231. var BlurPostProcess = /** @class */ (function (_super) {
  75232. __extends(BlurPostProcess, _super);
  75233. /**
  75234. * Creates a new instance BlurPostProcess
  75235. * @param name The name of the effect.
  75236. * @param direction The direction in which to blur the image.
  75237. * @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.
  75238. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75239. * @param camera The camera to apply the render pass to.
  75240. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75241. * @param engine The engine which the post process will be applied. (default: current engine)
  75242. * @param reusable If the post process can be reused on the same frame. (default: false)
  75243. * @param textureType Type of textures used when performing the post process. (default: 0)
  75244. * @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)
  75245. */
  75246. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75247. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75248. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75249. if (defines === void 0) { defines = ""; }
  75250. if (blockCompilation === void 0) { blockCompilation = false; }
  75251. 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;
  75252. _this.direction = direction;
  75253. _this.blockCompilation = blockCompilation;
  75254. _this._packedFloat = false;
  75255. _this._staticDefines = "";
  75256. _this._staticDefines = defines;
  75257. _this.onApplyObservable.add(function (effect) {
  75258. if (_this._outputTexture) {
  75259. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75260. }
  75261. else {
  75262. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75263. }
  75264. });
  75265. _this.kernel = kernel;
  75266. return _this;
  75267. }
  75268. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75269. /**
  75270. * Gets the length in pixels of the blur sample region
  75271. */
  75272. get: function () {
  75273. return this._idealKernel;
  75274. },
  75275. /**
  75276. * Sets the length in pixels of the blur sample region
  75277. */
  75278. set: function (v) {
  75279. if (this._idealKernel === v) {
  75280. return;
  75281. }
  75282. v = Math.max(v, 1);
  75283. this._idealKernel = v;
  75284. this._kernel = this._nearestBestKernel(v);
  75285. if (!this.blockCompilation) {
  75286. this._updateParameters();
  75287. }
  75288. },
  75289. enumerable: true,
  75290. configurable: true
  75291. });
  75292. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75293. /**
  75294. * Gets wether or not the blur is unpacking/repacking floats
  75295. */
  75296. get: function () {
  75297. return this._packedFloat;
  75298. },
  75299. /**
  75300. * Sets wether or not the blur needs to unpack/repack floats
  75301. */
  75302. set: function (v) {
  75303. if (this._packedFloat === v) {
  75304. return;
  75305. }
  75306. this._packedFloat = v;
  75307. if (!this.blockCompilation) {
  75308. this._updateParameters();
  75309. }
  75310. },
  75311. enumerable: true,
  75312. configurable: true
  75313. });
  75314. /**
  75315. * Updates the effect with the current post process compile time values and recompiles the shader.
  75316. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75317. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75318. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75319. * @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
  75320. * @param onCompiled Called when the shader has been compiled.
  75321. * @param onError Called if there is an error when compiling a shader.
  75322. */
  75323. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75324. if (defines === void 0) { defines = null; }
  75325. if (uniforms === void 0) { uniforms = null; }
  75326. if (samplers === void 0) { samplers = null; }
  75327. this._updateParameters(onCompiled, onError);
  75328. };
  75329. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75330. // Generate sampling offsets and weights
  75331. var N = this._kernel;
  75332. var centerIndex = (N - 1) / 2;
  75333. // Generate Gaussian sampling weights over kernel
  75334. var offsets = [];
  75335. var weights = [];
  75336. var totalWeight = 0;
  75337. for (var i = 0; i < N; i++) {
  75338. var u = i / (N - 1);
  75339. var w = this._gaussianWeight(u * 2.0 - 1);
  75340. offsets[i] = (i - centerIndex);
  75341. weights[i] = w;
  75342. totalWeight += w;
  75343. }
  75344. // Normalize weights
  75345. for (var i = 0; i < weights.length; i++) {
  75346. weights[i] /= totalWeight;
  75347. }
  75348. // Optimize: combine samples to take advantage of hardware linear sampling
  75349. // Walk from left to center, combining pairs (symmetrically)
  75350. var linearSamplingWeights = [];
  75351. var linearSamplingOffsets = [];
  75352. var linearSamplingMap = [];
  75353. for (var i = 0; i <= centerIndex; i += 2) {
  75354. var j = Math.min(i + 1, Math.floor(centerIndex));
  75355. var singleCenterSample = i === j;
  75356. if (singleCenterSample) {
  75357. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75358. }
  75359. else {
  75360. var sharedCell = j === centerIndex;
  75361. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75362. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75363. if (offsetLinear === 0) {
  75364. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75365. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75366. }
  75367. else {
  75368. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75369. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75370. }
  75371. }
  75372. }
  75373. for (var i = 0; i < linearSamplingMap.length; i++) {
  75374. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75375. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75376. }
  75377. // Replace with optimized
  75378. offsets = linearSamplingOffsets;
  75379. weights = linearSamplingWeights;
  75380. // Generate shaders
  75381. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75382. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75383. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75384. var defines = "";
  75385. defines += this._staticDefines;
  75386. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75387. if (this._staticDefines.indexOf("DOF") != -1) {
  75388. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75389. varyingCount--;
  75390. }
  75391. for (var i = 0; i < varyingCount; i++) {
  75392. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75393. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75394. }
  75395. var depCount = 0;
  75396. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75397. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75398. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75399. depCount++;
  75400. }
  75401. if (this.packedFloat) {
  75402. defines += "#define PACKEDFLOAT 1";
  75403. }
  75404. this.blockCompilation = false;
  75405. _super.prototype.updateEffect.call(this, defines, null, null, {
  75406. varyingCount: varyingCount,
  75407. depCount: depCount
  75408. }, onCompiled, onError);
  75409. };
  75410. /**
  75411. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75412. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75413. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75414. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75415. * The gaps between physical kernels are compensated for in the weighting of the samples
  75416. * @param idealKernel Ideal blur kernel.
  75417. * @return Nearest best kernel.
  75418. */
  75419. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75420. var v = Math.round(idealKernel);
  75421. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75422. var k = _a[_i];
  75423. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75424. return Math.max(k, 3);
  75425. }
  75426. }
  75427. return Math.max(v, 3);
  75428. };
  75429. /**
  75430. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75431. * @param x The point on the Gaussian distribution to sample.
  75432. * @return the value of the Gaussian function at x.
  75433. */
  75434. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75435. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75436. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75437. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75438. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75439. // truncated at around 1.3% of peak strength.
  75440. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75441. var sigma = (1 / 3);
  75442. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75443. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75444. var weight = (1.0 / denominator) * Math.exp(exponent);
  75445. return weight;
  75446. };
  75447. /**
  75448. * Generates a string that can be used as a floating point number in GLSL.
  75449. * @param x Value to print.
  75450. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75451. * @return GLSL float string.
  75452. */
  75453. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75454. if (decimalFigures === void 0) { decimalFigures = 8; }
  75455. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75456. };
  75457. return BlurPostProcess;
  75458. }(BABYLON.PostProcess));
  75459. BABYLON.BlurPostProcess = BlurPostProcess;
  75460. })(BABYLON || (BABYLON = {}));
  75461. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75462. var BABYLON;
  75463. (function (BABYLON) {
  75464. /**
  75465. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75466. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75467. * based on samples that have a large difference in distance than the center pixel.
  75468. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75469. */
  75470. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75471. __extends(DepthOfFieldBlurPostProcess, _super);
  75472. /**
  75473. * Creates a new instance CircleOfConfusionPostProcess
  75474. * @param name The name of the effect.
  75475. * @param scene The scene the effect belongs to.
  75476. * @param direction The direction the blur should be applied.
  75477. * @param kernel The size of the kernel used to blur.
  75478. * @param options The required width/height ratio to downsize to before computing the render pass.
  75479. * @param camera The camera to apply the render pass to.
  75480. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75481. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75482. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75483. * @param engine The engine which the post process will be applied. (default: current engine)
  75484. * @param reusable If the post process can be reused on the same frame. (default: false)
  75485. * @param textureType Type of textures used when performing the post process. (default: 0)
  75486. * @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)
  75487. */
  75488. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75489. if (imageToBlur === void 0) { imageToBlur = null; }
  75490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75491. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75492. if (blockCompilation === void 0) { blockCompilation = false; }
  75493. 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;
  75494. _this.direction = direction;
  75495. _this.onApplyObservable.add(function (effect) {
  75496. if (imageToBlur != null) {
  75497. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75498. }
  75499. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75500. if (scene.activeCamera) {
  75501. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75502. }
  75503. });
  75504. return _this;
  75505. }
  75506. return DepthOfFieldBlurPostProcess;
  75507. }(BABYLON.BlurPostProcess));
  75508. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75509. })(BABYLON || (BABYLON = {}));
  75510. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75511. var BABYLON;
  75512. (function (BABYLON) {
  75513. /**
  75514. * Options to be set when merging outputs from the default pipeline.
  75515. */
  75516. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75517. function DepthOfFieldMergePostProcessOptions() {
  75518. }
  75519. return DepthOfFieldMergePostProcessOptions;
  75520. }());
  75521. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75522. /**
  75523. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75524. */
  75525. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75526. __extends(DepthOfFieldMergePostProcess, _super);
  75527. /**
  75528. * Creates a new instance of DepthOfFieldMergePostProcess
  75529. * @param name The name of the effect.
  75530. * @param originalFromInput Post process which's input will be used for the merge.
  75531. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75532. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75533. * @param options The required width/height ratio to downsize to before computing the render pass.
  75534. * @param camera The camera to apply the render pass to.
  75535. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75536. * @param engine The engine which the post process will be applied. (default: current engine)
  75537. * @param reusable If the post process can be reused on the same frame. (default: false)
  75538. * @param textureType Type of textures used when performing the post process. (default: 0)
  75539. * @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)
  75540. */
  75541. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75542. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75543. if (blockCompilation === void 0) { blockCompilation = false; }
  75544. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75545. _this.blurSteps = blurSteps;
  75546. _this.onApplyObservable.add(function (effect) {
  75547. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75548. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75549. blurSteps.forEach(function (step, index) {
  75550. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75551. });
  75552. });
  75553. if (!blockCompilation) {
  75554. _this.updateEffect();
  75555. }
  75556. return _this;
  75557. }
  75558. /**
  75559. * Updates the effect with the current post process compile time values and recompiles the shader.
  75560. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75561. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75562. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75563. * @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
  75564. * @param onCompiled Called when the shader has been compiled.
  75565. * @param onError Called if there is an error when compiling a shader.
  75566. */
  75567. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75568. if (defines === void 0) { defines = null; }
  75569. if (uniforms === void 0) { uniforms = null; }
  75570. if (samplers === void 0) { samplers = null; }
  75571. if (!defines) {
  75572. defines = "";
  75573. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75574. }
  75575. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75576. };
  75577. return DepthOfFieldMergePostProcess;
  75578. }(BABYLON.PostProcess));
  75579. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75580. })(BABYLON || (BABYLON = {}));
  75581. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75582. var BABYLON;
  75583. (function (BABYLON) {
  75584. /**
  75585. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75586. */
  75587. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75588. __extends(CircleOfConfusionPostProcess, _super);
  75589. /**
  75590. * Creates a new instance CircleOfConfusionPostProcess
  75591. * @param name The name of the effect.
  75592. * @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.
  75593. * @param options The required width/height ratio to downsize to before computing the render pass.
  75594. * @param camera The camera to apply the render pass to.
  75595. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75596. * @param engine The engine which the post process will be applied. (default: current engine)
  75597. * @param reusable If the post process can be reused on the same frame. (default: false)
  75598. * @param textureType Type of textures used when performing the post process. (default: 0)
  75599. * @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)
  75600. */
  75601. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75602. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75603. if (blockCompilation === void 0) { blockCompilation = false; }
  75604. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75605. /**
  75606. * 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.
  75607. */
  75608. _this.lensSize = 50;
  75609. /**
  75610. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75611. */
  75612. _this.fStop = 1.4;
  75613. /**
  75614. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75615. */
  75616. _this.focusDistance = 2000;
  75617. /**
  75618. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75619. */
  75620. _this.focalLength = 50;
  75621. _this._depthTexture = null;
  75622. _this._depthTexture = depthTexture;
  75623. _this.onApplyObservable.add(function (effect) {
  75624. if (!_this._depthTexture) {
  75625. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75626. return;
  75627. }
  75628. effect.setTexture("depthSampler", _this._depthTexture);
  75629. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75630. var aperture = _this.lensSize / _this.fStop;
  75631. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75632. effect.setFloat('focusDistance', _this.focusDistance);
  75633. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75634. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75635. });
  75636. return _this;
  75637. }
  75638. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75639. /**
  75640. * 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.
  75641. */
  75642. set: function (value) {
  75643. this._depthTexture = value;
  75644. },
  75645. enumerable: true,
  75646. configurable: true
  75647. });
  75648. return CircleOfConfusionPostProcess;
  75649. }(BABYLON.PostProcess));
  75650. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75651. })(BABYLON || (BABYLON = {}));
  75652. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75653. var BABYLON;
  75654. (function (BABYLON) {
  75655. /**
  75656. * Specifies the level of max blur that should be applied when using the depth of field effect
  75657. */
  75658. var DepthOfFieldEffectBlurLevel;
  75659. (function (DepthOfFieldEffectBlurLevel) {
  75660. /**
  75661. * Subtle blur
  75662. */
  75663. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75664. /**
  75665. * Medium blur
  75666. */
  75667. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75668. /**
  75669. * Large blur
  75670. */
  75671. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75672. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75673. ;
  75674. /**
  75675. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75676. */
  75677. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75678. __extends(DepthOfFieldEffect, _super);
  75679. /**
  75680. * Creates a new instance DepthOfFieldEffect
  75681. * @param scene The scene the effect belongs to.
  75682. * @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.
  75683. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75684. * @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)
  75685. */
  75686. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75687. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75688. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75689. if (blockCompilation === void 0) { blockCompilation = false; }
  75690. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75691. return _this._effects;
  75692. }, true) || this;
  75693. /**
  75694. * Internal post processes in depth of field effect
  75695. */
  75696. _this._effects = [];
  75697. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75698. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75699. // 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)
  75700. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75701. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75702. _this._depthOfFieldBlurY = [];
  75703. _this._depthOfFieldBlurX = [];
  75704. var blurCount = 1;
  75705. var kernelSize = 15;
  75706. switch (blurLevel) {
  75707. case DepthOfFieldEffectBlurLevel.High: {
  75708. blurCount = 3;
  75709. kernelSize = 51;
  75710. break;
  75711. }
  75712. case DepthOfFieldEffectBlurLevel.Medium: {
  75713. blurCount = 2;
  75714. kernelSize = 31;
  75715. break;
  75716. }
  75717. default: {
  75718. kernelSize = 15;
  75719. blurCount = 1;
  75720. break;
  75721. }
  75722. }
  75723. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75724. var ratio = 1.0;
  75725. for (var i = 0; i < blurCount; i++) {
  75726. 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);
  75727. blurY.autoClear = false;
  75728. ratio = 0.75 / Math.pow(2, i);
  75729. 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);
  75730. blurX.autoClear = false;
  75731. _this._depthOfFieldBlurY.push(blurY);
  75732. _this._depthOfFieldBlurX.push(blurX);
  75733. }
  75734. // Set all post processes on the effect.
  75735. _this._effects = [_this._circleOfConfusion];
  75736. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75737. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75738. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75739. }
  75740. // Merge blurred images with original image based on circleOfConfusion
  75741. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75742. _this._dofMerge.autoClear = false;
  75743. _this._effects.push(_this._dofMerge);
  75744. return _this;
  75745. }
  75746. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75747. get: function () {
  75748. return this._circleOfConfusion.focalLength;
  75749. },
  75750. /**
  75751. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75752. */
  75753. set: function (value) {
  75754. this._circleOfConfusion.focalLength = value;
  75755. },
  75756. enumerable: true,
  75757. configurable: true
  75758. });
  75759. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75760. get: function () {
  75761. return this._circleOfConfusion.fStop;
  75762. },
  75763. /**
  75764. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75765. */
  75766. set: function (value) {
  75767. this._circleOfConfusion.fStop = value;
  75768. },
  75769. enumerable: true,
  75770. configurable: true
  75771. });
  75772. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75773. get: function () {
  75774. return this._circleOfConfusion.focusDistance;
  75775. },
  75776. /**
  75777. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75778. */
  75779. set: function (value) {
  75780. this._circleOfConfusion.focusDistance = value;
  75781. },
  75782. enumerable: true,
  75783. configurable: true
  75784. });
  75785. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75786. get: function () {
  75787. return this._circleOfConfusion.lensSize;
  75788. },
  75789. /**
  75790. * 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.
  75791. */
  75792. set: function (value) {
  75793. this._circleOfConfusion.lensSize = value;
  75794. },
  75795. enumerable: true,
  75796. configurable: true
  75797. });
  75798. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75799. /**
  75800. * 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.
  75801. */
  75802. set: function (value) {
  75803. this._circleOfConfusion.depthTexture = value;
  75804. },
  75805. enumerable: true,
  75806. configurable: true
  75807. });
  75808. /**
  75809. * Disposes each of the internal effects for a given camera.
  75810. * @param camera The camera to dispose the effect on.
  75811. */
  75812. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75813. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75814. this._effects[effectIndex].dispose(camera);
  75815. }
  75816. };
  75817. /**
  75818. * Internal
  75819. */
  75820. DepthOfFieldEffect.prototype._updateEffects = function () {
  75821. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75822. this._effects[effectIndex].updateEffect();
  75823. }
  75824. };
  75825. /**
  75826. * Internal
  75827. * @returns if all the contained post processes are ready.
  75828. */
  75829. DepthOfFieldEffect.prototype._isReady = function () {
  75830. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75831. if (!this._effects[effectIndex].isReady()) {
  75832. return false;
  75833. }
  75834. }
  75835. return true;
  75836. };
  75837. return DepthOfFieldEffect;
  75838. }(BABYLON.PostProcessRenderEffect));
  75839. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75840. })(BABYLON || (BABYLON = {}));
  75841. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75842. var BABYLON;
  75843. (function (BABYLON) {
  75844. /**
  75845. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75846. */
  75847. var BloomMergePostProcess = /** @class */ (function (_super) {
  75848. __extends(BloomMergePostProcess, _super);
  75849. /**
  75850. * Creates a new instance of @see BloomMergePostProcess
  75851. * @param name The name of the effect.
  75852. * @param originalFromInput Post process which's input will be used for the merge.
  75853. * @param blurred Blurred highlights post process which's output will be used.
  75854. * @param weight Weight of the bloom to be added to the original input.
  75855. * @param options The required width/height ratio to downsize to before computing the render pass.
  75856. * @param camera The camera to apply the render pass to.
  75857. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75858. * @param engine The engine which the post process will be applied. (default: current engine)
  75859. * @param reusable If the post process can be reused on the same frame. (default: false)
  75860. * @param textureType Type of textures used when performing the post process. (default: 0)
  75861. * @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)
  75862. */
  75863. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75864. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75865. if (blockCompilation === void 0) { blockCompilation = false; }
  75866. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75867. _this.weight = weight;
  75868. _this.onApplyObservable.add(function (effect) {
  75869. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75870. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75871. effect.setFloat("bloomWeight", _this.weight);
  75872. });
  75873. if (!blockCompilation) {
  75874. _this.updateEffect();
  75875. }
  75876. return _this;
  75877. }
  75878. return BloomMergePostProcess;
  75879. }(BABYLON.PostProcess));
  75880. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75881. })(BABYLON || (BABYLON = {}));
  75882. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75883. var BABYLON;
  75884. (function (BABYLON) {
  75885. /**
  75886. * 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.
  75887. */
  75888. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75889. __extends(ExtractHighlightsPostProcess, _super);
  75890. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75891. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75892. if (blockCompilation === void 0) { blockCompilation = false; }
  75893. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75894. /**
  75895. * The luminance threshold, pixels below this value will be set to black.
  75896. */
  75897. _this.threshold = 0.9;
  75898. /**
  75899. * Internal
  75900. */
  75901. _this._exposure = 1;
  75902. /**
  75903. * Post process which has the input texture to be used when performing highlight extraction
  75904. */
  75905. _this._inputPostProcess = null;
  75906. _this.onApplyObservable.add(function (effect) {
  75907. if (_this._inputPostProcess) {
  75908. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75909. }
  75910. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75911. effect.setFloat('exposure', _this._exposure);
  75912. });
  75913. return _this;
  75914. }
  75915. return ExtractHighlightsPostProcess;
  75916. }(BABYLON.PostProcess));
  75917. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75918. })(BABYLON || (BABYLON = {}));
  75919. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75920. var BABYLON;
  75921. (function (BABYLON) {
  75922. /**
  75923. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75924. */
  75925. var BloomEffect = /** @class */ (function (_super) {
  75926. __extends(BloomEffect, _super);
  75927. /**
  75928. * Creates a new instance of @see BloomEffect
  75929. * @param scene The scene the effect belongs to.
  75930. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75931. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75932. * @param bloomWeight The the strength of bloom.
  75933. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75934. * @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)
  75935. */
  75936. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75937. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75938. if (blockCompilation === void 0) { blockCompilation = false; }
  75939. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75940. return _this._effects;
  75941. }, true) || this;
  75942. _this.bloomScale = bloomScale;
  75943. /**
  75944. * Internal
  75945. */
  75946. _this._effects = [];
  75947. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75948. _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);
  75949. _this._blurX.alwaysForcePOT = true;
  75950. _this._blurX.autoClear = false;
  75951. _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);
  75952. _this._blurY.alwaysForcePOT = true;
  75953. _this._blurY.autoClear = false;
  75954. _this.kernel = bloomKernel;
  75955. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75956. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75957. _this._merge.autoClear = false;
  75958. _this._effects.push(_this._merge);
  75959. return _this;
  75960. }
  75961. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75962. /**
  75963. * The luminance threshold to find bright areas of the image to bloom.
  75964. */
  75965. get: function () {
  75966. return this._downscale.threshold;
  75967. },
  75968. set: function (value) {
  75969. this._downscale.threshold = value;
  75970. },
  75971. enumerable: true,
  75972. configurable: true
  75973. });
  75974. Object.defineProperty(BloomEffect.prototype, "weight", {
  75975. /**
  75976. * The strength of the bloom.
  75977. */
  75978. get: function () {
  75979. return this._merge.weight;
  75980. },
  75981. set: function (value) {
  75982. this._merge.weight = value;
  75983. },
  75984. enumerable: true,
  75985. configurable: true
  75986. });
  75987. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75988. /**
  75989. * Specifies the size of the bloom blur kernel, relative to the final output size
  75990. */
  75991. get: function () {
  75992. return this._blurX.kernel / this.bloomScale;
  75993. },
  75994. set: function (value) {
  75995. this._blurX.kernel = value * this.bloomScale;
  75996. this._blurY.kernel = value * this.bloomScale;
  75997. },
  75998. enumerable: true,
  75999. configurable: true
  76000. });
  76001. /**
  76002. * Disposes each of the internal effects for a given camera.
  76003. * @param camera The camera to dispose the effect on.
  76004. */
  76005. BloomEffect.prototype.disposeEffects = function (camera) {
  76006. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76007. this._effects[effectIndex].dispose(camera);
  76008. }
  76009. };
  76010. /**
  76011. * Internal
  76012. */
  76013. BloomEffect.prototype._updateEffects = function () {
  76014. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76015. this._effects[effectIndex].updateEffect();
  76016. }
  76017. };
  76018. /**
  76019. * Internal
  76020. * @returns if all the contained post processes are ready.
  76021. */
  76022. BloomEffect.prototype._isReady = function () {
  76023. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76024. if (!this._effects[effectIndex].isReady()) {
  76025. return false;
  76026. }
  76027. }
  76028. return true;
  76029. };
  76030. return BloomEffect;
  76031. }(BABYLON.PostProcessRenderEffect));
  76032. BABYLON.BloomEffect = BloomEffect;
  76033. })(BABYLON || (BABYLON = {}));
  76034. //# sourceMappingURL=babylon.bloomEffect.js.map
  76035. var BABYLON;
  76036. (function (BABYLON) {
  76037. /**
  76038. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76039. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76040. */
  76041. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76042. __extends(DefaultRenderingPipeline, _super);
  76043. /**
  76044. * @constructor
  76045. * @param {string} name - The rendering pipeline name (default: "")
  76046. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76047. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76048. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76049. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76050. */
  76051. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76052. if (name === void 0) { name = ""; }
  76053. if (hdr === void 0) { hdr = true; }
  76054. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76055. if (automaticBuild === void 0) { automaticBuild = true; }
  76056. var _this = _super.call(this, scene.getEngine(), name) || this;
  76057. _this._originalCameras = [];
  76058. /**
  76059. * ID of the sharpen post process,
  76060. */
  76061. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76062. /**
  76063. * ID of the image processing post process;
  76064. */
  76065. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76066. /**
  76067. * ID of the Fast Approximate Anti-Aliasing post process;
  76068. */
  76069. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76070. /**
  76071. * ID of the chromatic aberration post process,
  76072. */
  76073. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76074. /**
  76075. * ID of the grain post process
  76076. */
  76077. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76078. /**
  76079. * Glow post process which adds a glow to emmisive areas of the image
  76080. */
  76081. _this._glowLayer = null;
  76082. /**
  76083. * Animations which can be used to tweak settings over a period of time
  76084. */
  76085. _this.animations = [];
  76086. _this._imageProcessingConfigurationObserver = null;
  76087. // Values
  76088. _this._sharpenEnabled = false;
  76089. _this._bloomEnabled = false;
  76090. _this._depthOfFieldEnabled = false;
  76091. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76092. _this._fxaaEnabled = false;
  76093. _this._imageProcessingEnabled = true;
  76094. _this._bloomScale = 0.5;
  76095. _this._chromaticAberrationEnabled = false;
  76096. _this._grainEnabled = false;
  76097. _this._buildAllowed = true;
  76098. _this._resizeObserver = null;
  76099. _this._hardwareScaleLevel = 1.0;
  76100. _this._bloomKernel = 64;
  76101. /**
  76102. * Specifies the weight of the bloom in the final rendering
  76103. */
  76104. _this._bloomWeight = 0.15;
  76105. /**
  76106. * Specifies the luma threshold for the area that will be blurred by the bloom
  76107. */
  76108. _this._bloomThreshold = 0.9;
  76109. _this._samples = 1;
  76110. _this._hasCleared = false;
  76111. _this._prevPostProcess = null;
  76112. _this._prevPrevPostProcess = null;
  76113. _this._cameras = cameras || scene.cameras;
  76114. _this._originalCameras = _this._cameras.slice();
  76115. _this._buildAllowed = automaticBuild;
  76116. // Initialize
  76117. _this._scene = scene;
  76118. var caps = _this._scene.getEngine().getCaps();
  76119. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76120. // Misc
  76121. if (_this._hdr) {
  76122. if (caps.textureHalfFloatRender) {
  76123. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76124. }
  76125. else if (caps.textureFloatRender) {
  76126. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76127. }
  76128. }
  76129. else {
  76130. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76131. }
  76132. // Attach
  76133. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76134. var engine = _this._scene.getEngine();
  76135. // Create post processes before hand so they can be modified before enabled.
  76136. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76137. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76138. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76139. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76140. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76141. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76142. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76143. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76144. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76145. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76146. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76147. _this.bloomKernel = _this.bloomKernel;
  76148. });
  76149. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76150. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76151. });
  76152. _this._buildPipeline();
  76153. return _this;
  76154. }
  76155. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76156. get: function () {
  76157. return this._sharpenEnabled;
  76158. },
  76159. /**
  76160. * Enable or disable the sharpen process from the pipeline
  76161. */
  76162. set: function (enabled) {
  76163. if (this._sharpenEnabled === enabled) {
  76164. return;
  76165. }
  76166. this._sharpenEnabled = enabled;
  76167. this._buildPipeline();
  76168. },
  76169. enumerable: true,
  76170. configurable: true
  76171. });
  76172. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76173. /**
  76174. * Specifies the size of the bloom blur kernel, relative to the final output size
  76175. */
  76176. get: function () {
  76177. return this._bloomKernel;
  76178. },
  76179. set: function (value) {
  76180. this._bloomKernel = value;
  76181. this.bloom.kernel = value / this._hardwareScaleLevel;
  76182. },
  76183. enumerable: true,
  76184. configurable: true
  76185. });
  76186. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76187. get: function () {
  76188. return this._bloomWeight;
  76189. },
  76190. /**
  76191. * The strength of the bloom.
  76192. */
  76193. set: function (value) {
  76194. if (this._bloomWeight === value) {
  76195. return;
  76196. }
  76197. this.bloom.weight = value;
  76198. this._bloomWeight = value;
  76199. },
  76200. enumerable: true,
  76201. configurable: true
  76202. });
  76203. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76204. get: function () {
  76205. return this._bloomThreshold;
  76206. },
  76207. /**
  76208. * The strength of the bloom.
  76209. */
  76210. set: function (value) {
  76211. if (this._bloomThreshold === value) {
  76212. return;
  76213. }
  76214. this.bloom.threshold = value;
  76215. this._bloomThreshold = value;
  76216. },
  76217. enumerable: true,
  76218. configurable: true
  76219. });
  76220. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76221. get: function () {
  76222. return this._bloomScale;
  76223. },
  76224. /**
  76225. * The scale of the bloom, lower value will provide better performance.
  76226. */
  76227. set: function (value) {
  76228. if (this._bloomScale === value) {
  76229. return;
  76230. }
  76231. this._bloomScale = value;
  76232. // recreate bloom and dispose old as this setting is not dynamic
  76233. this._rebuildBloom();
  76234. this._buildPipeline();
  76235. },
  76236. enumerable: true,
  76237. configurable: true
  76238. });
  76239. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76240. get: function () {
  76241. return this._bloomEnabled;
  76242. },
  76243. /**
  76244. * Enable or disable the bloom from the pipeline
  76245. */
  76246. set: function (enabled) {
  76247. if (this._bloomEnabled === enabled) {
  76248. return;
  76249. }
  76250. this._bloomEnabled = enabled;
  76251. this._buildPipeline();
  76252. },
  76253. enumerable: true,
  76254. configurable: true
  76255. });
  76256. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76257. // recreate bloom and dispose old as this setting is not dynamic
  76258. var oldBloom = this.bloom;
  76259. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76260. this.bloom.threshold = oldBloom.threshold;
  76261. for (var i = 0; i < this._cameras.length; i++) {
  76262. oldBloom.disposeEffects(this._cameras[i]);
  76263. }
  76264. };
  76265. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76266. /**
  76267. * If the depth of field is enabled.
  76268. */
  76269. get: function () {
  76270. return this._depthOfFieldEnabled;
  76271. },
  76272. set: function (enabled) {
  76273. if (this._depthOfFieldEnabled === enabled) {
  76274. return;
  76275. }
  76276. this._depthOfFieldEnabled = enabled;
  76277. this._buildPipeline();
  76278. },
  76279. enumerable: true,
  76280. configurable: true
  76281. });
  76282. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76283. /**
  76284. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76285. */
  76286. get: function () {
  76287. return this._depthOfFieldBlurLevel;
  76288. },
  76289. set: function (value) {
  76290. if (this._depthOfFieldBlurLevel === value) {
  76291. return;
  76292. }
  76293. this._depthOfFieldBlurLevel = value;
  76294. // recreate dof and dispose old as this setting is not dynamic
  76295. var oldDof = this.depthOfField;
  76296. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76297. this.depthOfField.focalLength = oldDof.focalLength;
  76298. this.depthOfField.focusDistance = oldDof.focusDistance;
  76299. this.depthOfField.fStop = oldDof.fStop;
  76300. this.depthOfField.lensSize = oldDof.lensSize;
  76301. for (var i = 0; i < this._cameras.length; i++) {
  76302. oldDof.disposeEffects(this._cameras[i]);
  76303. }
  76304. this._buildPipeline();
  76305. },
  76306. enumerable: true,
  76307. configurable: true
  76308. });
  76309. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76310. get: function () {
  76311. return this._fxaaEnabled;
  76312. },
  76313. /**
  76314. * If the anti aliasing is enabled.
  76315. */
  76316. set: function (enabled) {
  76317. if (this._fxaaEnabled === enabled) {
  76318. return;
  76319. }
  76320. this._fxaaEnabled = enabled;
  76321. this._buildPipeline();
  76322. },
  76323. enumerable: true,
  76324. configurable: true
  76325. });
  76326. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76327. get: function () {
  76328. return this._samples;
  76329. },
  76330. /**
  76331. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76332. */
  76333. set: function (sampleCount) {
  76334. if (this._samples === sampleCount) {
  76335. return;
  76336. }
  76337. this._samples = sampleCount;
  76338. this._buildPipeline();
  76339. },
  76340. enumerable: true,
  76341. configurable: true
  76342. });
  76343. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76344. get: function () {
  76345. return this._imageProcessingEnabled;
  76346. },
  76347. /**
  76348. * If image processing is enabled.
  76349. */
  76350. set: function (enabled) {
  76351. if (this._imageProcessingEnabled === enabled) {
  76352. return;
  76353. }
  76354. this._imageProcessingEnabled = enabled;
  76355. this._buildPipeline();
  76356. },
  76357. enumerable: true,
  76358. configurable: true
  76359. });
  76360. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76361. get: function () {
  76362. return this._glowLayer == null;
  76363. },
  76364. /**
  76365. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76366. */
  76367. set: function (enabled) {
  76368. if (enabled && !this._glowLayer) {
  76369. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76370. }
  76371. else if (!enabled && this._glowLayer) {
  76372. this._glowLayer.dispose();
  76373. this._glowLayer = null;
  76374. }
  76375. },
  76376. enumerable: true,
  76377. configurable: true
  76378. });
  76379. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76380. get: function () {
  76381. return this._chromaticAberrationEnabled;
  76382. },
  76383. /**
  76384. * Enable or disable the chromaticAberration process from the pipeline
  76385. */
  76386. set: function (enabled) {
  76387. if (this._chromaticAberrationEnabled === enabled) {
  76388. return;
  76389. }
  76390. this._chromaticAberrationEnabled = enabled;
  76391. this._buildPipeline();
  76392. },
  76393. enumerable: true,
  76394. configurable: true
  76395. });
  76396. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76397. get: function () {
  76398. return this._grainEnabled;
  76399. },
  76400. /**
  76401. * Enable or disable the grain process from the pipeline
  76402. */
  76403. set: function (enabled) {
  76404. if (this._grainEnabled === enabled) {
  76405. return;
  76406. }
  76407. this._grainEnabled = enabled;
  76408. this._buildPipeline();
  76409. },
  76410. enumerable: true,
  76411. configurable: true
  76412. });
  76413. /**
  76414. * Force the compilation of the entire pipeline.
  76415. */
  76416. DefaultRenderingPipeline.prototype.prepare = function () {
  76417. var previousState = this._buildAllowed;
  76418. this._buildAllowed = true;
  76419. this._buildPipeline();
  76420. this._buildAllowed = previousState;
  76421. };
  76422. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76423. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76424. if (this._hasCleared) {
  76425. postProcess.autoClear = false;
  76426. }
  76427. else {
  76428. postProcess.autoClear = true;
  76429. this._scene.autoClear = false;
  76430. this._hasCleared = true;
  76431. }
  76432. if (!skipTextureSharing) {
  76433. if (this._prevPrevPostProcess) {
  76434. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76435. }
  76436. else {
  76437. postProcess.useOwnOutput();
  76438. }
  76439. if (this._prevPostProcess) {
  76440. this._prevPrevPostProcess = this._prevPostProcess;
  76441. }
  76442. this._prevPostProcess = postProcess;
  76443. }
  76444. };
  76445. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76446. var _this = this;
  76447. if (!this._buildAllowed) {
  76448. return;
  76449. }
  76450. this._scene.autoClear = true;
  76451. var engine = this._scene.getEngine();
  76452. this._disposePostProcesses();
  76453. if (this._cameras !== null) {
  76454. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76455. // get back cameras to be used to reattach pipeline
  76456. this._cameras = this._originalCameras.slice();
  76457. }
  76458. this._reset();
  76459. this._prevPostProcess = null;
  76460. this._prevPrevPostProcess = null;
  76461. this._hasCleared = false;
  76462. if (this.depthOfFieldEnabled) {
  76463. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76464. this.depthOfField.depthTexture = depthTexture;
  76465. if (!this.depthOfField._isReady()) {
  76466. this.depthOfField._updateEffects();
  76467. }
  76468. this.addEffect(this.depthOfField);
  76469. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76470. }
  76471. if (this.bloomEnabled) {
  76472. if (!this.bloom._isReady()) {
  76473. this.bloom._updateEffects();
  76474. }
  76475. this.addEffect(this.bloom);
  76476. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76477. }
  76478. if (this._imageProcessingEnabled) {
  76479. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76480. if (this._hdr) {
  76481. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76482. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76483. }
  76484. else {
  76485. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76486. }
  76487. }
  76488. if (this.sharpenEnabled) {
  76489. if (!this.sharpen.isReady()) {
  76490. this.sharpen.updateEffect();
  76491. }
  76492. this.addEffect(this._sharpenEffect);
  76493. this._setAutoClearAndTextureSharing(this.sharpen);
  76494. }
  76495. if (this.grainEnabled) {
  76496. if (!this.grain.isReady()) {
  76497. this.grain.updateEffect();
  76498. }
  76499. this.addEffect(this._grainEffect);
  76500. this._setAutoClearAndTextureSharing(this.grain);
  76501. }
  76502. if (this.chromaticAberrationEnabled) {
  76503. if (!this.chromaticAberration.isReady()) {
  76504. this.chromaticAberration.updateEffect();
  76505. }
  76506. this.addEffect(this._chromaticAberrationEffect);
  76507. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76508. }
  76509. if (this.fxaaEnabled) {
  76510. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76511. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76512. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76513. }
  76514. if (this._cameras !== null) {
  76515. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76516. }
  76517. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76518. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76519. }
  76520. };
  76521. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76522. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76523. for (var i = 0; i < this._cameras.length; i++) {
  76524. var camera = this._cameras[i];
  76525. if (this.imageProcessing) {
  76526. this.imageProcessing.dispose(camera);
  76527. }
  76528. if (this.fxaa) {
  76529. this.fxaa.dispose(camera);
  76530. }
  76531. // These are created in the constructor and should not be disposed on every pipeline change
  76532. if (disposeNonRecreated) {
  76533. if (this.sharpen) {
  76534. this.sharpen.dispose(camera);
  76535. }
  76536. if (this.depthOfField) {
  76537. this.depthOfField.disposeEffects(camera);
  76538. }
  76539. if (this.bloom) {
  76540. this.bloom.disposeEffects(camera);
  76541. }
  76542. if (this.chromaticAberration) {
  76543. this.chromaticAberration.dispose(camera);
  76544. }
  76545. if (this.grain) {
  76546. this.grain.dispose(camera);
  76547. }
  76548. if (this._glowLayer) {
  76549. this._glowLayer.dispose();
  76550. }
  76551. }
  76552. }
  76553. this.imageProcessing = null;
  76554. this.fxaa = null;
  76555. if (disposeNonRecreated) {
  76556. this.sharpen = null;
  76557. this._sharpenEffect = null;
  76558. this.depthOfField = null;
  76559. this.bloom = null;
  76560. this.chromaticAberration = null;
  76561. this._chromaticAberrationEffect = null;
  76562. this.grain = null;
  76563. this._grainEffect = null;
  76564. this._glowLayer = null;
  76565. }
  76566. };
  76567. /**
  76568. * Dispose of the pipeline and stop all post processes
  76569. */
  76570. DefaultRenderingPipeline.prototype.dispose = function () {
  76571. this._disposePostProcesses(true);
  76572. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76573. this._scene.autoClear = true;
  76574. if (this._resizeObserver) {
  76575. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76576. this._resizeObserver = null;
  76577. }
  76578. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76579. _super.prototype.dispose.call(this);
  76580. };
  76581. /**
  76582. * Serialize the rendering pipeline (Used when exporting)
  76583. * @returns the serialized object
  76584. */
  76585. DefaultRenderingPipeline.prototype.serialize = function () {
  76586. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76587. serializationObject.customType = "DefaultRenderingPipeline";
  76588. return serializationObject;
  76589. };
  76590. /**
  76591. * Parse the serialized pipeline
  76592. * @param source Source pipeline.
  76593. * @param scene The scene to load the pipeline to.
  76594. * @param rootUrl The URL of the serialized pipeline.
  76595. * @returns An instantiated pipeline from the serialized object.
  76596. */
  76597. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76598. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76599. };
  76600. __decorate([
  76601. BABYLON.serialize()
  76602. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76603. __decorate([
  76604. BABYLON.serialize()
  76605. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76606. __decorate([
  76607. BABYLON.serialize()
  76608. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76609. __decorate([
  76610. BABYLON.serialize()
  76611. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76612. __decorate([
  76613. BABYLON.serialize()
  76614. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76615. __decorate([
  76616. BABYLON.serialize()
  76617. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76618. __decorate([
  76619. BABYLON.serialize()
  76620. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76621. __decorate([
  76622. BABYLON.serialize()
  76623. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76624. __decorate([
  76625. BABYLON.serialize()
  76626. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76627. __decorate([
  76628. BABYLON.serialize()
  76629. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76630. __decorate([
  76631. BABYLON.serialize()
  76632. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76633. __decorate([
  76634. BABYLON.serialize()
  76635. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76636. __decorate([
  76637. BABYLON.serialize()
  76638. ], DefaultRenderingPipeline.prototype, "samples", null);
  76639. __decorate([
  76640. BABYLON.serialize()
  76641. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76642. __decorate([
  76643. BABYLON.serialize()
  76644. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76645. __decorate([
  76646. BABYLON.serialize()
  76647. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76648. __decorate([
  76649. BABYLON.serialize()
  76650. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76651. return DefaultRenderingPipeline;
  76652. }(BABYLON.PostProcessRenderPipeline));
  76653. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76654. })(BABYLON || (BABYLON = {}));
  76655. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76656. var BABYLON;
  76657. (function (BABYLON) {
  76658. /**
  76659. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76660. */
  76661. var GeometryBufferRenderer = /** @class */ (function () {
  76662. /**
  76663. * Creates a new G Buffer for the scene
  76664. * @param scene The scene the buffer belongs to
  76665. * @param ratio How big is the buffer related to the main canvas.
  76666. */
  76667. function GeometryBufferRenderer(scene, ratio) {
  76668. if (ratio === void 0) { ratio = 1; }
  76669. this._enablePosition = false;
  76670. this._scene = scene;
  76671. this._ratio = ratio;
  76672. // Render target
  76673. this._createRenderTargets();
  76674. }
  76675. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76676. /**
  76677. * Set the render list (meshes to be rendered) used in the G buffer.
  76678. */
  76679. set: function (meshes) {
  76680. this._multiRenderTarget.renderList = meshes;
  76681. },
  76682. enumerable: true,
  76683. configurable: true
  76684. });
  76685. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76686. /**
  76687. * Gets wether or not G buffer are supported by the running hardware.
  76688. * This requires draw buffer supports
  76689. */
  76690. get: function () {
  76691. return this._multiRenderTarget.isSupported;
  76692. },
  76693. enumerable: true,
  76694. configurable: true
  76695. });
  76696. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76697. /**
  76698. * Gets wether or not position are enabled for the G buffer.
  76699. */
  76700. get: function () {
  76701. return this._enablePosition;
  76702. },
  76703. /**
  76704. * Sets wether or not position are enabled for the G buffer.
  76705. */
  76706. set: function (enable) {
  76707. this._enablePosition = enable;
  76708. this.dispose();
  76709. this._createRenderTargets();
  76710. },
  76711. enumerable: true,
  76712. configurable: true
  76713. });
  76714. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76715. /**
  76716. * Gets the scene associated with the buffer.
  76717. */
  76718. get: function () {
  76719. return this._scene;
  76720. },
  76721. enumerable: true,
  76722. configurable: true
  76723. });
  76724. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76725. /**
  76726. * Gets the ratio used by the buffer during its creation.
  76727. * How big is the buffer related to the main canvas.
  76728. */
  76729. get: function () {
  76730. return this._ratio;
  76731. },
  76732. enumerable: true,
  76733. configurable: true
  76734. });
  76735. /**
  76736. * Checks wether everything is ready to render a submesh to the G buffer.
  76737. * @param subMesh the submesh to check readiness for
  76738. * @param useInstances is the mesh drawn using instance or not
  76739. * @returns true if ready otherwise false
  76740. */
  76741. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76742. var material = subMesh.getMaterial();
  76743. if (material && material.disableDepthWrite) {
  76744. return false;
  76745. }
  76746. var defines = [];
  76747. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76748. var mesh = subMesh.getMesh();
  76749. // Alpha test
  76750. if (material && material.needAlphaTesting()) {
  76751. defines.push("#define ALPHATEST");
  76752. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76753. attribs.push(BABYLON.VertexBuffer.UVKind);
  76754. defines.push("#define UV1");
  76755. }
  76756. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76757. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76758. defines.push("#define UV2");
  76759. }
  76760. }
  76761. // Buffers
  76762. if (this._enablePosition) {
  76763. defines.push("#define POSITION");
  76764. }
  76765. // Bones
  76766. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76767. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76768. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76769. if (mesh.numBoneInfluencers > 4) {
  76770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76772. }
  76773. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76774. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76775. }
  76776. else {
  76777. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76778. }
  76779. // Instances
  76780. if (useInstances) {
  76781. defines.push("#define INSTANCES");
  76782. attribs.push("world0");
  76783. attribs.push("world1");
  76784. attribs.push("world2");
  76785. attribs.push("world3");
  76786. }
  76787. // Get correct effect
  76788. var join = defines.join("\n");
  76789. if (this._cachedDefines !== join) {
  76790. this._cachedDefines = join;
  76791. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76792. }
  76793. return this._effect.isReady();
  76794. };
  76795. /**
  76796. * Gets the current underlying G Buffer.
  76797. * @returns the buffer
  76798. */
  76799. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76800. return this._multiRenderTarget;
  76801. };
  76802. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76803. /**
  76804. * Gets the number of samples used to render the buffer (anti aliasing).
  76805. */
  76806. get: function () {
  76807. return this._multiRenderTarget.samples;
  76808. },
  76809. /**
  76810. * Sets the number of samples used to render the buffer (anti aliasing).
  76811. */
  76812. set: function (value) {
  76813. this._multiRenderTarget.samples = value;
  76814. },
  76815. enumerable: true,
  76816. configurable: true
  76817. });
  76818. /**
  76819. * Disposes the renderer and frees up associated resources.
  76820. */
  76821. GeometryBufferRenderer.prototype.dispose = function () {
  76822. this.getGBuffer().dispose();
  76823. };
  76824. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76825. var _this = this;
  76826. var engine = this._scene.getEngine();
  76827. var count = this._enablePosition ? 3 : 2;
  76828. 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 });
  76829. if (!this.isSupported) {
  76830. return;
  76831. }
  76832. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76833. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76834. this._multiRenderTarget.refreshRate = 1;
  76835. this._multiRenderTarget.renderParticles = false;
  76836. this._multiRenderTarget.renderList = null;
  76837. // set default depth value to 1.0 (far away)
  76838. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76839. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76840. });
  76841. // Custom render function
  76842. var renderSubMesh = function (subMesh) {
  76843. var mesh = subMesh.getRenderingMesh();
  76844. var scene = _this._scene;
  76845. var engine = scene.getEngine();
  76846. var material = subMesh.getMaterial();
  76847. if (!material) {
  76848. return;
  76849. }
  76850. // Culling
  76851. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76852. // Managing instances
  76853. var batch = mesh._getInstancesRenderList(subMesh._id);
  76854. if (batch.mustReturn) {
  76855. return;
  76856. }
  76857. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76858. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76859. engine.enableEffect(_this._effect);
  76860. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76861. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76862. _this._effect.setMatrix("view", scene.getViewMatrix());
  76863. // Alpha test
  76864. if (material && material.needAlphaTesting()) {
  76865. var alphaTexture = material.getAlphaTestTexture();
  76866. if (alphaTexture) {
  76867. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76868. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76869. }
  76870. }
  76871. // Bones
  76872. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76873. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76874. }
  76875. // Draw
  76876. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76877. }
  76878. };
  76879. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76880. var index;
  76881. if (depthOnlySubMeshes.length) {
  76882. engine.setColorWrite(false);
  76883. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76884. renderSubMesh(depthOnlySubMeshes.data[index]);
  76885. }
  76886. engine.setColorWrite(true);
  76887. }
  76888. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76889. renderSubMesh(opaqueSubMeshes.data[index]);
  76890. }
  76891. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76892. renderSubMesh(alphaTestSubMeshes.data[index]);
  76893. }
  76894. };
  76895. };
  76896. return GeometryBufferRenderer;
  76897. }());
  76898. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76899. })(BABYLON || (BABYLON = {}));
  76900. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76901. var BABYLON;
  76902. (function (BABYLON) {
  76903. var RefractionPostProcess = /** @class */ (function (_super) {
  76904. __extends(RefractionPostProcess, _super);
  76905. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76906. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76907. _this.color = color;
  76908. _this.depth = depth;
  76909. _this.colorLevel = colorLevel;
  76910. _this._ownRefractionTexture = true;
  76911. _this.onActivateObservable.add(function (cam) {
  76912. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76913. });
  76914. _this.onApplyObservable.add(function (effect) {
  76915. effect.setColor3("baseColor", _this.color);
  76916. effect.setFloat("depth", _this.depth);
  76917. effect.setFloat("colorLevel", _this.colorLevel);
  76918. effect.setTexture("refractionSampler", _this._refTexture);
  76919. });
  76920. return _this;
  76921. }
  76922. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76923. /**
  76924. * Gets or sets the refraction texture
  76925. * Please note that you are responsible for disposing the texture if you set it manually
  76926. */
  76927. get: function () {
  76928. return this._refTexture;
  76929. },
  76930. set: function (value) {
  76931. if (this._refTexture && this._ownRefractionTexture) {
  76932. this._refTexture.dispose();
  76933. }
  76934. this._refTexture = value;
  76935. this._ownRefractionTexture = false;
  76936. },
  76937. enumerable: true,
  76938. configurable: true
  76939. });
  76940. // Methods
  76941. RefractionPostProcess.prototype.dispose = function (camera) {
  76942. if (this._refTexture && this._ownRefractionTexture) {
  76943. this._refTexture.dispose();
  76944. this._refTexture = null;
  76945. }
  76946. _super.prototype.dispose.call(this, camera);
  76947. };
  76948. return RefractionPostProcess;
  76949. }(BABYLON.PostProcess));
  76950. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76951. })(BABYLON || (BABYLON = {}));
  76952. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76953. var BABYLON;
  76954. (function (BABYLON) {
  76955. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76956. __extends(BlackAndWhitePostProcess, _super);
  76957. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76958. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76959. _this.degree = 1;
  76960. _this.onApplyObservable.add(function (effect) {
  76961. effect.setFloat("degree", _this.degree);
  76962. });
  76963. return _this;
  76964. }
  76965. return BlackAndWhitePostProcess;
  76966. }(BABYLON.PostProcess));
  76967. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76968. })(BABYLON || (BABYLON = {}));
  76969. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76970. var BABYLON;
  76971. (function (BABYLON) {
  76972. /**
  76973. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76974. * input texture to perform effects such as edge detection or sharpening
  76975. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76976. */
  76977. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76978. __extends(ConvolutionPostProcess, _super);
  76979. /**
  76980. * Creates a new instance ConvolutionPostProcess
  76981. * @param name The name of the effect.
  76982. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76983. * @param options The required width/height ratio to downsize to before computing the render pass.
  76984. * @param camera The camera to apply the render pass to.
  76985. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76986. * @param engine The engine which the post process will be applied. (default: current engine)
  76987. * @param reusable If the post process can be reused on the same frame. (default: false)
  76988. * @param textureType Type of textures used when performing the post process. (default: 0)
  76989. */
  76990. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76991. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76992. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76993. _this.kernel = kernel;
  76994. _this.onApply = function (effect) {
  76995. effect.setFloat2("screenSize", _this.width, _this.height);
  76996. effect.setArray("kernel", _this.kernel);
  76997. };
  76998. return _this;
  76999. }
  77000. // Statics
  77001. /**
  77002. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77003. */
  77004. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77005. /**
  77006. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77007. */
  77008. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77009. /**
  77010. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77011. */
  77012. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77013. /**
  77014. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77015. */
  77016. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77017. /**
  77018. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77019. */
  77020. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77021. /**
  77022. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77023. */
  77024. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77025. return ConvolutionPostProcess;
  77026. }(BABYLON.PostProcess));
  77027. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77028. })(BABYLON || (BABYLON = {}));
  77029. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77030. var BABYLON;
  77031. (function (BABYLON) {
  77032. var FilterPostProcess = /** @class */ (function (_super) {
  77033. __extends(FilterPostProcess, _super);
  77034. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77035. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77036. _this.kernelMatrix = kernelMatrix;
  77037. _this.onApply = function (effect) {
  77038. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77039. };
  77040. return _this;
  77041. }
  77042. return FilterPostProcess;
  77043. }(BABYLON.PostProcess));
  77044. BABYLON.FilterPostProcess = FilterPostProcess;
  77045. })(BABYLON || (BABYLON = {}));
  77046. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77047. var BABYLON;
  77048. (function (BABYLON) {
  77049. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77050. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77051. __extends(VolumetricLightScatteringPostProcess, _super);
  77052. /**
  77053. * @constructor
  77054. * @param {string} name - The post-process name
  77055. * @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)
  77056. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77057. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77058. * @param {number} samples - The post-process quality, default 100
  77059. * @param {number} samplingMode - The post-process filtering mode
  77060. * @param {BABYLON.Engine} engine - The babylon engine
  77061. * @param {boolean} reusable - If the post-process is reusable
  77062. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77063. */
  77064. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77065. if (samples === void 0) { samples = 100; }
  77066. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77067. 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;
  77068. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77069. /**
  77070. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77071. */
  77072. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77073. /**
  77074. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77075. */
  77076. _this.useCustomMeshPosition = false;
  77077. /**
  77078. * If the post-process should inverse the light scattering direction
  77079. */
  77080. _this.invert = true;
  77081. /**
  77082. * Array containing the excluded meshes not rendered in the internal pass
  77083. */
  77084. _this.excludedMeshes = new Array();
  77085. /**
  77086. * Controls the overall intensity of the post-process
  77087. */
  77088. _this.exposure = 0.3;
  77089. /**
  77090. * Dissipates each sample's contribution in range [0, 1]
  77091. */
  77092. _this.decay = 0.96815;
  77093. /**
  77094. * Controls the overall intensity of each sample
  77095. */
  77096. _this.weight = 0.58767;
  77097. /**
  77098. * Controls the density of each sample
  77099. */
  77100. _this.density = 0.926;
  77101. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77102. engine = scene.getEngine();
  77103. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77104. // Configure mesh
  77105. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77106. // Configure
  77107. _this._createPass(scene, ratio.passRatio || ratio);
  77108. _this.onActivate = function (camera) {
  77109. if (!_this.isSupported) {
  77110. _this.dispose(camera);
  77111. }
  77112. _this.onActivate = null;
  77113. };
  77114. _this.onApplyObservable.add(function (effect) {
  77115. _this._updateMeshScreenCoordinates(scene);
  77116. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77117. effect.setFloat("exposure", _this.exposure);
  77118. effect.setFloat("decay", _this.decay);
  77119. effect.setFloat("weight", _this.weight);
  77120. effect.setFloat("density", _this.density);
  77121. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77122. });
  77123. return _this;
  77124. }
  77125. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77126. get: function () {
  77127. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77128. return false;
  77129. },
  77130. set: function (useDiffuseColor) {
  77131. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77132. },
  77133. enumerable: true,
  77134. configurable: true
  77135. });
  77136. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77137. return "VolumetricLightScatteringPostProcess";
  77138. };
  77139. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77140. var mesh = subMesh.getMesh();
  77141. // Render this.mesh as default
  77142. if (mesh === this.mesh && mesh.material) {
  77143. return mesh.material.isReady(mesh);
  77144. }
  77145. var defines = [];
  77146. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77147. var material = subMesh.getMaterial();
  77148. // Alpha test
  77149. if (material) {
  77150. if (material.needAlphaTesting()) {
  77151. defines.push("#define ALPHATEST");
  77152. }
  77153. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77154. attribs.push(BABYLON.VertexBuffer.UVKind);
  77155. defines.push("#define UV1");
  77156. }
  77157. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77158. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77159. defines.push("#define UV2");
  77160. }
  77161. }
  77162. // Bones
  77163. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77164. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77165. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77166. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77167. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77168. }
  77169. else {
  77170. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77171. }
  77172. // Instances
  77173. if (useInstances) {
  77174. defines.push("#define INSTANCES");
  77175. attribs.push("world0");
  77176. attribs.push("world1");
  77177. attribs.push("world2");
  77178. attribs.push("world3");
  77179. }
  77180. // Get correct effect
  77181. var join = defines.join("\n");
  77182. if (this._cachedDefines !== join) {
  77183. this._cachedDefines = join;
  77184. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77185. }
  77186. return this._volumetricLightScatteringPass.isReady();
  77187. };
  77188. /**
  77189. * Sets the new light position for light scattering effect
  77190. * @param {BABYLON.Vector3} The new custom light position
  77191. */
  77192. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77193. this.customMeshPosition = position;
  77194. };
  77195. /**
  77196. * Returns the light position for light scattering effect
  77197. * @return {BABYLON.Vector3} The custom light position
  77198. */
  77199. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77200. return this.customMeshPosition;
  77201. };
  77202. /**
  77203. * Disposes the internal assets and detaches the post-process from the camera
  77204. */
  77205. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77206. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77207. if (rttIndex !== -1) {
  77208. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77209. }
  77210. this._volumetricLightScatteringRTT.dispose();
  77211. _super.prototype.dispose.call(this, camera);
  77212. };
  77213. /**
  77214. * Returns the render target texture used by the post-process
  77215. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77216. */
  77217. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77218. return this._volumetricLightScatteringRTT;
  77219. };
  77220. // Private methods
  77221. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77222. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77223. return true;
  77224. }
  77225. return false;
  77226. };
  77227. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77228. var _this = this;
  77229. var engine = scene.getEngine();
  77230. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77231. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77232. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77233. this._volumetricLightScatteringRTT.renderList = null;
  77234. this._volumetricLightScatteringRTT.renderParticles = false;
  77235. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77236. var camera = this.getCamera();
  77237. if (camera) {
  77238. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77239. }
  77240. else {
  77241. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77242. }
  77243. // Custom render function for submeshes
  77244. var renderSubMesh = function (subMesh) {
  77245. var mesh = subMesh.getRenderingMesh();
  77246. if (_this._meshExcluded(mesh)) {
  77247. return;
  77248. }
  77249. var material = subMesh.getMaterial();
  77250. if (!material) {
  77251. return;
  77252. }
  77253. var scene = mesh.getScene();
  77254. var engine = scene.getEngine();
  77255. // Culling
  77256. engine.setState(material.backFaceCulling);
  77257. // Managing instances
  77258. var batch = mesh._getInstancesRenderList(subMesh._id);
  77259. if (batch.mustReturn) {
  77260. return;
  77261. }
  77262. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77263. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77264. var effect = _this._volumetricLightScatteringPass;
  77265. if (mesh === _this.mesh) {
  77266. if (subMesh.effect) {
  77267. effect = subMesh.effect;
  77268. }
  77269. else {
  77270. effect = material.getEffect();
  77271. }
  77272. }
  77273. engine.enableEffect(effect);
  77274. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77275. if (mesh === _this.mesh) {
  77276. material.bind(mesh.getWorldMatrix(), mesh);
  77277. }
  77278. else {
  77279. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77280. // Alpha test
  77281. if (material && material.needAlphaTesting()) {
  77282. var alphaTexture = material.getAlphaTestTexture();
  77283. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77284. if (alphaTexture) {
  77285. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77286. }
  77287. }
  77288. // Bones
  77289. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77290. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77291. }
  77292. }
  77293. // Draw
  77294. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77295. }
  77296. };
  77297. // Render target texture callbacks
  77298. var savedSceneClearColor;
  77299. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77300. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77301. savedSceneClearColor = scene.clearColor;
  77302. scene.clearColor = sceneClearColor;
  77303. });
  77304. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77305. scene.clearColor = savedSceneClearColor;
  77306. });
  77307. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77308. var engine = scene.getEngine();
  77309. var index;
  77310. if (depthOnlySubMeshes.length) {
  77311. engine.setColorWrite(false);
  77312. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77313. renderSubMesh(depthOnlySubMeshes.data[index]);
  77314. }
  77315. engine.setColorWrite(true);
  77316. }
  77317. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77318. renderSubMesh(opaqueSubMeshes.data[index]);
  77319. }
  77320. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77321. renderSubMesh(alphaTestSubMeshes.data[index]);
  77322. }
  77323. if (transparentSubMeshes.length) {
  77324. // Sort sub meshes
  77325. for (index = 0; index < transparentSubMeshes.length; index++) {
  77326. var submesh = transparentSubMeshes.data[index];
  77327. var boundingInfo = submesh.getBoundingInfo();
  77328. if (boundingInfo && scene.activeCamera) {
  77329. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77330. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77331. }
  77332. }
  77333. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77334. sortedArray.sort(function (a, b) {
  77335. // Alpha index first
  77336. if (a._alphaIndex > b._alphaIndex) {
  77337. return 1;
  77338. }
  77339. if (a._alphaIndex < b._alphaIndex) {
  77340. return -1;
  77341. }
  77342. // Then distance to camera
  77343. if (a._distanceToCamera < b._distanceToCamera) {
  77344. return 1;
  77345. }
  77346. if (a._distanceToCamera > b._distanceToCamera) {
  77347. return -1;
  77348. }
  77349. return 0;
  77350. });
  77351. // Render sub meshes
  77352. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77353. for (index = 0; index < sortedArray.length; index++) {
  77354. renderSubMesh(sortedArray[index]);
  77355. }
  77356. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77357. }
  77358. };
  77359. };
  77360. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77361. var transform = scene.getTransformMatrix();
  77362. var meshPosition;
  77363. if (this.useCustomMeshPosition) {
  77364. meshPosition = this.customMeshPosition;
  77365. }
  77366. else if (this.attachedNode) {
  77367. meshPosition = this.attachedNode.position;
  77368. }
  77369. else {
  77370. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77371. }
  77372. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77373. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77374. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77375. if (this.invert)
  77376. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77377. };
  77378. // Static methods
  77379. /**
  77380. * Creates a default mesh for the Volumeric Light Scattering post-process
  77381. * @param {string} The mesh name
  77382. * @param {BABYLON.Scene} The scene where to create the mesh
  77383. * @return {BABYLON.Mesh} the default mesh
  77384. */
  77385. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77386. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77387. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77388. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77389. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77390. mesh.material = material;
  77391. return mesh;
  77392. };
  77393. __decorate([
  77394. BABYLON.serializeAsVector3()
  77395. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77396. __decorate([
  77397. BABYLON.serialize()
  77398. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77399. __decorate([
  77400. BABYLON.serialize()
  77401. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77402. __decorate([
  77403. BABYLON.serializeAsMeshReference()
  77404. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77405. __decorate([
  77406. BABYLON.serialize()
  77407. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77408. __decorate([
  77409. BABYLON.serialize()
  77410. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77411. __decorate([
  77412. BABYLON.serialize()
  77413. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77414. __decorate([
  77415. BABYLON.serialize()
  77416. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77417. __decorate([
  77418. BABYLON.serialize()
  77419. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77420. return VolumetricLightScatteringPostProcess;
  77421. }(BABYLON.PostProcess));
  77422. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77423. })(BABYLON || (BABYLON = {}));
  77424. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77425. //
  77426. // This post-process allows the modification of rendered colors by using
  77427. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77428. //
  77429. // The object needs to be provided an url to a texture containing the color
  77430. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77431. // Use an image editing software to tweak the LUT to match your needs.
  77432. //
  77433. // For an example of a color LUT, see here:
  77434. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77435. // For explanations on color grading, see here:
  77436. // http://udn.epicgames.com/Three/ColorGrading.html
  77437. //
  77438. var BABYLON;
  77439. (function (BABYLON) {
  77440. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77441. __extends(ColorCorrectionPostProcess, _super);
  77442. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77443. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77444. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77445. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77446. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77447. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77448. _this.onApply = function (effect) {
  77449. effect.setTexture("colorTable", _this._colorTableTexture);
  77450. };
  77451. return _this;
  77452. }
  77453. return ColorCorrectionPostProcess;
  77454. }(BABYLON.PostProcess));
  77455. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77456. })(BABYLON || (BABYLON = {}));
  77457. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77458. var BABYLON;
  77459. (function (BABYLON) {
  77460. /** Defines operator used for tonemapping */
  77461. var TonemappingOperator;
  77462. (function (TonemappingOperator) {
  77463. /** Hable */
  77464. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77465. /** Reinhard */
  77466. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77467. /** HejiDawson */
  77468. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77469. /** Photographic */
  77470. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77471. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77472. ;
  77473. /**
  77474. * Defines a post process to apply tone mapping
  77475. */
  77476. var TonemapPostProcess = /** @class */ (function (_super) {
  77477. __extends(TonemapPostProcess, _super);
  77478. /**
  77479. * Creates a new TonemapPostProcess
  77480. * @param name defines the name of the postprocess
  77481. * @param _operator defines the operator to use
  77482. * @param exposureAdjustment defines the required exposure adjustement
  77483. * @param camera defines the camera to use (can be null)
  77484. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77485. * @param engine defines the hosting engine (can be ignore if camera is set)
  77486. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77487. */
  77488. function TonemapPostProcess(name, _operator,
  77489. /** Defines the required exposure adjustement */
  77490. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77491. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77492. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77493. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77494. _this._operator = _operator;
  77495. _this.exposureAdjustment = exposureAdjustment;
  77496. var defines = "#define ";
  77497. if (_this._operator === TonemappingOperator.Hable)
  77498. defines += "HABLE_TONEMAPPING";
  77499. else if (_this._operator === TonemappingOperator.Reinhard)
  77500. defines += "REINHARD_TONEMAPPING";
  77501. else if (_this._operator === TonemappingOperator.HejiDawson)
  77502. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77503. else if (_this._operator === TonemappingOperator.Photographic)
  77504. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77505. //sadly a second call to create the effect.
  77506. _this.updateEffect(defines);
  77507. _this.onApply = function (effect) {
  77508. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77509. };
  77510. return _this;
  77511. }
  77512. return TonemapPostProcess;
  77513. }(BABYLON.PostProcess));
  77514. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77515. })(BABYLON || (BABYLON = {}));
  77516. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77517. var BABYLON;
  77518. (function (BABYLON) {
  77519. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77520. __extends(DisplayPassPostProcess, _super);
  77521. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77522. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77523. }
  77524. return DisplayPassPostProcess;
  77525. }(BABYLON.PostProcess));
  77526. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77527. })(BABYLON || (BABYLON = {}));
  77528. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77529. var BABYLON;
  77530. (function (BABYLON) {
  77531. var HighlightsPostProcess = /** @class */ (function (_super) {
  77532. __extends(HighlightsPostProcess, _super);
  77533. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77534. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77535. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77536. }
  77537. return HighlightsPostProcess;
  77538. }(BABYLON.PostProcess));
  77539. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77540. })(BABYLON || (BABYLON = {}));
  77541. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77542. var BABYLON;
  77543. (function (BABYLON) {
  77544. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77545. __extends(ImageProcessingPostProcess, _super);
  77546. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77547. if (camera === void 0) { camera = null; }
  77548. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77549. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77550. _this._fromLinearSpace = true;
  77551. /**
  77552. * Defines cache preventing GC.
  77553. */
  77554. _this._defines = {
  77555. IMAGEPROCESSING: false,
  77556. VIGNETTE: false,
  77557. VIGNETTEBLENDMODEMULTIPLY: false,
  77558. VIGNETTEBLENDMODEOPAQUE: false,
  77559. TONEMAPPING: false,
  77560. CONTRAST: false,
  77561. COLORCURVES: false,
  77562. COLORGRADING: false,
  77563. COLORGRADING3D: false,
  77564. FROMLINEARSPACE: false,
  77565. SAMPLER3DGREENDEPTH: false,
  77566. SAMPLER3DBGRMAP: false,
  77567. IMAGEPROCESSINGPOSTPROCESS: false,
  77568. EXPOSURE: false,
  77569. };
  77570. // Setup the configuration as forced by the constructor. This would then not force the
  77571. // scene materials output in linear space and let untouched the default forward pass.
  77572. if (imageProcessingConfiguration) {
  77573. imageProcessingConfiguration.applyByPostProcess = true;
  77574. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77575. // This will cause the shader to be compiled
  77576. _this.fromLinearSpace = false;
  77577. }
  77578. // Setup the default processing configuration to the scene.
  77579. else {
  77580. _this._attachImageProcessingConfiguration(null, true);
  77581. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77582. }
  77583. _this.onApply = function (effect) {
  77584. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77585. };
  77586. return _this;
  77587. }
  77588. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77589. /**
  77590. * Gets the image processing configuration used either in this material.
  77591. */
  77592. get: function () {
  77593. return this._imageProcessingConfiguration;
  77594. },
  77595. /**
  77596. * Sets the Default image processing configuration used either in the this material.
  77597. *
  77598. * If sets to null, the scene one is in use.
  77599. */
  77600. set: function (value) {
  77601. this._attachImageProcessingConfiguration(value);
  77602. },
  77603. enumerable: true,
  77604. configurable: true
  77605. });
  77606. /**
  77607. * Attaches a new image processing configuration to the PBR Material.
  77608. * @param configuration
  77609. */
  77610. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77611. var _this = this;
  77612. if (doNotBuild === void 0) { doNotBuild = false; }
  77613. if (configuration === this._imageProcessingConfiguration) {
  77614. return;
  77615. }
  77616. // Detaches observer.
  77617. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77618. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77619. }
  77620. // Pick the scene configuration if needed.
  77621. if (!configuration) {
  77622. var scene = null;
  77623. var engine = this.getEngine();
  77624. var camera = this.getCamera();
  77625. if (camera) {
  77626. scene = camera.getScene();
  77627. }
  77628. else if (engine && engine.scenes) {
  77629. var scenes = engine.scenes;
  77630. scene = scenes[scenes.length - 1];
  77631. }
  77632. else {
  77633. scene = BABYLON.Engine.LastCreatedScene;
  77634. }
  77635. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77636. }
  77637. else {
  77638. this._imageProcessingConfiguration = configuration;
  77639. }
  77640. // Attaches observer.
  77641. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77642. _this._updateParameters();
  77643. });
  77644. // Ensure the effect will be rebuilt.
  77645. if (!doNotBuild) {
  77646. this._updateParameters();
  77647. }
  77648. };
  77649. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77650. /**
  77651. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77652. */
  77653. get: function () {
  77654. return this.imageProcessingConfiguration.colorCurves;
  77655. },
  77656. /**
  77657. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77658. */
  77659. set: function (value) {
  77660. this.imageProcessingConfiguration.colorCurves = value;
  77661. },
  77662. enumerable: true,
  77663. configurable: true
  77664. });
  77665. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77666. /**
  77667. * Gets wether the color curves effect is enabled.
  77668. */
  77669. get: function () {
  77670. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77671. },
  77672. /**
  77673. * Sets wether the color curves effect is enabled.
  77674. */
  77675. set: function (value) {
  77676. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77677. },
  77678. enumerable: true,
  77679. configurable: true
  77680. });
  77681. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77682. /**
  77683. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77684. */
  77685. get: function () {
  77686. return this.imageProcessingConfiguration.colorGradingTexture;
  77687. },
  77688. /**
  77689. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77690. */
  77691. set: function (value) {
  77692. this.imageProcessingConfiguration.colorGradingTexture = value;
  77693. },
  77694. enumerable: true,
  77695. configurable: true
  77696. });
  77697. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77698. /**
  77699. * Gets wether the color grading effect is enabled.
  77700. */
  77701. get: function () {
  77702. return this.imageProcessingConfiguration.colorGradingEnabled;
  77703. },
  77704. /**
  77705. * Gets wether the color grading effect is enabled.
  77706. */
  77707. set: function (value) {
  77708. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77709. },
  77710. enumerable: true,
  77711. configurable: true
  77712. });
  77713. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77714. /**
  77715. * Gets exposure used in the effect.
  77716. */
  77717. get: function () {
  77718. return this.imageProcessingConfiguration.exposure;
  77719. },
  77720. /**
  77721. * Sets exposure used in the effect.
  77722. */
  77723. set: function (value) {
  77724. this.imageProcessingConfiguration.exposure = value;
  77725. },
  77726. enumerable: true,
  77727. configurable: true
  77728. });
  77729. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77730. /**
  77731. * Gets wether tonemapping is enabled or not.
  77732. */
  77733. get: function () {
  77734. return this._imageProcessingConfiguration.toneMappingEnabled;
  77735. },
  77736. /**
  77737. * Sets wether tonemapping is enabled or not
  77738. */
  77739. set: function (value) {
  77740. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77741. },
  77742. enumerable: true,
  77743. configurable: true
  77744. });
  77745. ;
  77746. ;
  77747. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77748. /**
  77749. * Gets contrast used in the effect.
  77750. */
  77751. get: function () {
  77752. return this.imageProcessingConfiguration.contrast;
  77753. },
  77754. /**
  77755. * Sets contrast used in the effect.
  77756. */
  77757. set: function (value) {
  77758. this.imageProcessingConfiguration.contrast = value;
  77759. },
  77760. enumerable: true,
  77761. configurable: true
  77762. });
  77763. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77764. /**
  77765. * Gets Vignette stretch size.
  77766. */
  77767. get: function () {
  77768. return this.imageProcessingConfiguration.vignetteStretch;
  77769. },
  77770. /**
  77771. * Sets Vignette stretch size.
  77772. */
  77773. set: function (value) {
  77774. this.imageProcessingConfiguration.vignetteStretch = value;
  77775. },
  77776. enumerable: true,
  77777. configurable: true
  77778. });
  77779. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77780. /**
  77781. * Gets Vignette centre X Offset.
  77782. */
  77783. get: function () {
  77784. return this.imageProcessingConfiguration.vignetteCentreX;
  77785. },
  77786. /**
  77787. * Sets Vignette centre X Offset.
  77788. */
  77789. set: function (value) {
  77790. this.imageProcessingConfiguration.vignetteCentreX = value;
  77791. },
  77792. enumerable: true,
  77793. configurable: true
  77794. });
  77795. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77796. /**
  77797. * Gets Vignette centre Y Offset.
  77798. */
  77799. get: function () {
  77800. return this.imageProcessingConfiguration.vignetteCentreY;
  77801. },
  77802. /**
  77803. * Sets Vignette centre Y Offset.
  77804. */
  77805. set: function (value) {
  77806. this.imageProcessingConfiguration.vignetteCentreY = value;
  77807. },
  77808. enumerable: true,
  77809. configurable: true
  77810. });
  77811. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77812. /**
  77813. * Gets Vignette weight or intensity of the vignette effect.
  77814. */
  77815. get: function () {
  77816. return this.imageProcessingConfiguration.vignetteWeight;
  77817. },
  77818. /**
  77819. * Sets Vignette weight or intensity of the vignette effect.
  77820. */
  77821. set: function (value) {
  77822. this.imageProcessingConfiguration.vignetteWeight = value;
  77823. },
  77824. enumerable: true,
  77825. configurable: true
  77826. });
  77827. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77828. /**
  77829. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77830. * if vignetteEnabled is set to true.
  77831. */
  77832. get: function () {
  77833. return this.imageProcessingConfiguration.vignetteColor;
  77834. },
  77835. /**
  77836. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77837. * if vignetteEnabled is set to true.
  77838. */
  77839. set: function (value) {
  77840. this.imageProcessingConfiguration.vignetteColor = value;
  77841. },
  77842. enumerable: true,
  77843. configurable: true
  77844. });
  77845. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77846. /**
  77847. * Gets Camera field of view used by the Vignette effect.
  77848. */
  77849. get: function () {
  77850. return this.imageProcessingConfiguration.vignetteCameraFov;
  77851. },
  77852. /**
  77853. * Sets Camera field of view used by the Vignette effect.
  77854. */
  77855. set: function (value) {
  77856. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77857. },
  77858. enumerable: true,
  77859. configurable: true
  77860. });
  77861. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77862. /**
  77863. * Gets the vignette blend mode allowing different kind of effect.
  77864. */
  77865. get: function () {
  77866. return this.imageProcessingConfiguration.vignetteBlendMode;
  77867. },
  77868. /**
  77869. * Sets the vignette blend mode allowing different kind of effect.
  77870. */
  77871. set: function (value) {
  77872. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77873. },
  77874. enumerable: true,
  77875. configurable: true
  77876. });
  77877. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77878. /**
  77879. * Gets wether the vignette effect is enabled.
  77880. */
  77881. get: function () {
  77882. return this.imageProcessingConfiguration.vignetteEnabled;
  77883. },
  77884. /**
  77885. * Sets wether the vignette effect is enabled.
  77886. */
  77887. set: function (value) {
  77888. this.imageProcessingConfiguration.vignetteEnabled = value;
  77889. },
  77890. enumerable: true,
  77891. configurable: true
  77892. });
  77893. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77894. /**
  77895. * Gets wether the input of the processing is in Gamma or Linear Space.
  77896. */
  77897. get: function () {
  77898. return this._fromLinearSpace;
  77899. },
  77900. /**
  77901. * Sets wether the input of the processing is in Gamma or Linear Space.
  77902. */
  77903. set: function (value) {
  77904. if (this._fromLinearSpace === value) {
  77905. return;
  77906. }
  77907. this._fromLinearSpace = value;
  77908. this._updateParameters();
  77909. },
  77910. enumerable: true,
  77911. configurable: true
  77912. });
  77913. ImageProcessingPostProcess.prototype.getClassName = function () {
  77914. return "ImageProcessingPostProcess";
  77915. };
  77916. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77917. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77918. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77919. var defines = "";
  77920. for (var define in this._defines) {
  77921. if (this._defines[define]) {
  77922. defines += "#define " + define + ";\r\n";
  77923. }
  77924. }
  77925. var samplers = ["textureSampler"];
  77926. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77927. var uniforms = ["scale"];
  77928. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77929. this.updateEffect(defines, uniforms, samplers);
  77930. };
  77931. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77932. _super.prototype.dispose.call(this, camera);
  77933. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77934. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77935. }
  77936. this.imageProcessingConfiguration.applyByPostProcess = false;
  77937. };
  77938. __decorate([
  77939. BABYLON.serialize()
  77940. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77941. return ImageProcessingPostProcess;
  77942. }(BABYLON.PostProcess));
  77943. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77944. })(BABYLON || (BABYLON = {}));
  77945. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77946. var BABYLON;
  77947. (function (BABYLON) {
  77948. /**
  77949. * Class used to store bone information
  77950. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77951. */
  77952. var Bone = /** @class */ (function (_super) {
  77953. __extends(Bone, _super);
  77954. /**
  77955. * Create a new bone
  77956. * @param name defines the bone name
  77957. * @param skeleton defines the parent skeleton
  77958. * @param parentBone defines the parent (can be null if the bone is the root)
  77959. * @param localMatrix defines the local matrix
  77960. * @param restPose defines the rest pose matrix
  77961. * @param baseMatrix defines the base matrix
  77962. * @param index defines index of the bone in the hiearchy
  77963. */
  77964. function Bone(
  77965. /**
  77966. * defines the bone name
  77967. */
  77968. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77969. if (parentBone === void 0) { parentBone = null; }
  77970. if (localMatrix === void 0) { localMatrix = null; }
  77971. if (restPose === void 0) { restPose = null; }
  77972. if (baseMatrix === void 0) { baseMatrix = null; }
  77973. if (index === void 0) { index = null; }
  77974. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77975. _this.name = name;
  77976. /**
  77977. * Gets the list of child bones
  77978. */
  77979. _this.children = new Array();
  77980. /** Gets the animations associated with this bone */
  77981. _this.animations = new Array();
  77982. /**
  77983. * @hidden Internal only
  77984. * Set this value to map this bone to a different index in the transform matrices
  77985. * Set this value to -1 to exclude the bone from the transform matrices
  77986. */
  77987. _this._index = null;
  77988. _this._absoluteTransform = new BABYLON.Matrix();
  77989. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77990. _this._scalingDeterminant = 1;
  77991. _this._worldTransform = new BABYLON.Matrix();
  77992. _this._needToDecompose = true;
  77993. _this._needToCompose = false;
  77994. _this._skeleton = skeleton;
  77995. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77996. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77997. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77998. _this._index = index;
  77999. skeleton.bones.push(_this);
  78000. _this.setParent(parentBone, false);
  78001. if (baseMatrix || localMatrix) {
  78002. _this._updateDifferenceMatrix();
  78003. }
  78004. return _this;
  78005. }
  78006. Object.defineProperty(Bone.prototype, "_matrix", {
  78007. /** @hidden */
  78008. get: function () {
  78009. this._compose();
  78010. return this._localMatrix;
  78011. },
  78012. /** @hidden */
  78013. set: function (value) {
  78014. this._localMatrix.copyFrom(value);
  78015. this._needToDecompose = true;
  78016. },
  78017. enumerable: true,
  78018. configurable: true
  78019. });
  78020. // Members
  78021. /**
  78022. * Gets the parent skeleton
  78023. * @returns a skeleton
  78024. */
  78025. Bone.prototype.getSkeleton = function () {
  78026. return this._skeleton;
  78027. };
  78028. /**
  78029. * Gets parent bone
  78030. * @returns a bone or null if the bone is the root of the bone hierarchy
  78031. */
  78032. Bone.prototype.getParent = function () {
  78033. return this._parent;
  78034. };
  78035. /**
  78036. * Sets the parent bone
  78037. * @param parent defines the parent (can be null if the bone is the root)
  78038. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78039. */
  78040. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78041. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78042. if (this._parent === parent) {
  78043. return;
  78044. }
  78045. if (this._parent) {
  78046. var index = this._parent.children.indexOf(this);
  78047. if (index !== -1) {
  78048. this._parent.children.splice(index, 1);
  78049. }
  78050. }
  78051. this._parent = parent;
  78052. if (this._parent) {
  78053. this._parent.children.push(this);
  78054. }
  78055. if (updateDifferenceMatrix) {
  78056. this._updateDifferenceMatrix();
  78057. }
  78058. this.markAsDirty();
  78059. };
  78060. /**
  78061. * Gets the local matrix
  78062. * @returns a matrix
  78063. */
  78064. Bone.prototype.getLocalMatrix = function () {
  78065. this._compose();
  78066. return this._localMatrix;
  78067. };
  78068. /**
  78069. * Gets the base matrix (initial matrix which remains unchanged)
  78070. * @returns a matrix
  78071. */
  78072. Bone.prototype.getBaseMatrix = function () {
  78073. return this._baseMatrix;
  78074. };
  78075. /**
  78076. * Gets the rest pose matrix
  78077. * @returns a matrix
  78078. */
  78079. Bone.prototype.getRestPose = function () {
  78080. return this._restPose;
  78081. };
  78082. /**
  78083. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78084. */
  78085. Bone.prototype.getWorldMatrix = function () {
  78086. return this._worldTransform;
  78087. };
  78088. /**
  78089. * Sets the local matrix to rest pose matrix
  78090. */
  78091. Bone.prototype.returnToRest = function () {
  78092. this.updateMatrix(this._restPose.clone());
  78093. };
  78094. /**
  78095. * Gets the inverse of the absolute transform matrix.
  78096. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78097. * @returns a matrix
  78098. */
  78099. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78100. return this._invertedAbsoluteTransform;
  78101. };
  78102. /**
  78103. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78104. * @returns a matrix
  78105. */
  78106. Bone.prototype.getAbsoluteTransform = function () {
  78107. return this._absoluteTransform;
  78108. };
  78109. Object.defineProperty(Bone.prototype, "position", {
  78110. // Properties (matches AbstractMesh properties)
  78111. /** Gets or sets current position (in local space) */
  78112. get: function () {
  78113. this._decompose();
  78114. return this._localPosition;
  78115. },
  78116. set: function (newPosition) {
  78117. this._decompose();
  78118. this._localPosition.copyFrom(newPosition);
  78119. this._markAsDirtyAndCompose();
  78120. },
  78121. enumerable: true,
  78122. configurable: true
  78123. });
  78124. Object.defineProperty(Bone.prototype, "rotation", {
  78125. /** Gets or sets current rotation (in local space) */
  78126. get: function () {
  78127. return this.getRotation();
  78128. },
  78129. set: function (newRotation) {
  78130. this.setRotation(newRotation);
  78131. },
  78132. enumerable: true,
  78133. configurable: true
  78134. });
  78135. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78136. /** Gets or sets current rotation quaternion (in local space) */
  78137. get: function () {
  78138. this._decompose();
  78139. return this._localRotation;
  78140. },
  78141. set: function (newRotation) {
  78142. this.setRotationQuaternion(newRotation);
  78143. },
  78144. enumerable: true,
  78145. configurable: true
  78146. });
  78147. Object.defineProperty(Bone.prototype, "scaling", {
  78148. /** Gets or sets current scaling (in local space) */
  78149. get: function () {
  78150. return this.getScale();
  78151. },
  78152. set: function (newScaling) {
  78153. this.setScale(newScaling);
  78154. },
  78155. enumerable: true,
  78156. configurable: true
  78157. });
  78158. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78159. /**
  78160. * Gets the animation properties override
  78161. */
  78162. get: function () {
  78163. return this._skeleton.animationPropertiesOverride;
  78164. },
  78165. enumerable: true,
  78166. configurable: true
  78167. });
  78168. // Methods
  78169. Bone.prototype._decompose = function () {
  78170. if (!this._needToDecompose) {
  78171. return;
  78172. }
  78173. this._needToDecompose = false;
  78174. if (!this._localScaling) {
  78175. this._localScaling = BABYLON.Vector3.Zero();
  78176. this._localRotation = BABYLON.Quaternion.Zero();
  78177. this._localPosition = BABYLON.Vector3.Zero();
  78178. }
  78179. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78180. };
  78181. Bone.prototype._compose = function () {
  78182. if (!this._needToCompose) {
  78183. return;
  78184. }
  78185. this._needToCompose = false;
  78186. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78187. };
  78188. /**
  78189. * Update the base and local matrices
  78190. * @param matrix defines the new base or local matrix
  78191. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78192. * @param updateLocalMatrix defines if the local matrix should be updated
  78193. */
  78194. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78195. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78196. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78197. this._baseMatrix.copyFrom(matrix);
  78198. if (updateDifferenceMatrix) {
  78199. this._updateDifferenceMatrix();
  78200. }
  78201. if (updateLocalMatrix) {
  78202. this._localMatrix.copyFrom(matrix);
  78203. this._markAsDirtyAndDecompose();
  78204. }
  78205. else {
  78206. this.markAsDirty();
  78207. }
  78208. };
  78209. /** @hidden */
  78210. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78211. if (updateChildren === void 0) { updateChildren = true; }
  78212. if (!rootMatrix) {
  78213. rootMatrix = this._baseMatrix;
  78214. }
  78215. if (this._parent) {
  78216. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78217. }
  78218. else {
  78219. this._absoluteTransform.copyFrom(rootMatrix);
  78220. }
  78221. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78222. if (updateChildren) {
  78223. for (var index = 0; index < this.children.length; index++) {
  78224. this.children[index]._updateDifferenceMatrix();
  78225. }
  78226. }
  78227. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78228. };
  78229. /**
  78230. * Flag the bone as dirty (Forcing it to update everything)
  78231. */
  78232. Bone.prototype.markAsDirty = function () {
  78233. this._currentRenderId++;
  78234. this._childRenderId++;
  78235. this._skeleton._markAsDirty();
  78236. };
  78237. Bone.prototype._markAsDirtyAndCompose = function () {
  78238. this.markAsDirty();
  78239. this._needToCompose = true;
  78240. };
  78241. Bone.prototype._markAsDirtyAndDecompose = function () {
  78242. this.markAsDirty();
  78243. this._needToDecompose = true;
  78244. };
  78245. /**
  78246. * Copy an animation range from another bone
  78247. * @param source defines the source bone
  78248. * @param rangeName defines the range name to copy
  78249. * @param frameOffset defines the frame offset
  78250. * @param rescaleAsRequired defines if rescaling must be applied if required
  78251. * @param skelDimensionsRatio defines the scaling ratio
  78252. * @returns true if operation was successful
  78253. */
  78254. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78255. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78256. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78257. // all animation may be coming from a library skeleton, so may need to create animation
  78258. if (this.animations.length === 0) {
  78259. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78260. this.animations[0].setKeys([]);
  78261. }
  78262. // get animation info / verify there is such a range from the source bone
  78263. var sourceRange = source.animations[0].getRange(rangeName);
  78264. if (!sourceRange) {
  78265. return false;
  78266. }
  78267. var from = sourceRange.from;
  78268. var to = sourceRange.to;
  78269. var sourceKeys = source.animations[0].getKeys();
  78270. // rescaling prep
  78271. var sourceBoneLength = source.length;
  78272. var sourceParent = source.getParent();
  78273. var parent = this.getParent();
  78274. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78275. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78276. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78277. var destKeys = this.animations[0].getKeys();
  78278. // loop vars declaration
  78279. var orig;
  78280. var origTranslation;
  78281. var mat;
  78282. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78283. orig = sourceKeys[key];
  78284. if (orig.frame >= from && orig.frame <= to) {
  78285. if (rescaleAsRequired) {
  78286. mat = orig.value.clone();
  78287. // scale based on parent ratio, when bone has parent
  78288. if (parentScalingReqd) {
  78289. origTranslation = mat.getTranslation();
  78290. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78291. // scale based on skeleton dimension ratio when root bone, and value is passed
  78292. }
  78293. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78294. origTranslation = mat.getTranslation();
  78295. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78296. // use original when root bone, and no data for skelDimensionsRatio
  78297. }
  78298. else {
  78299. mat = orig.value;
  78300. }
  78301. }
  78302. else {
  78303. mat = orig.value;
  78304. }
  78305. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78306. }
  78307. }
  78308. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78309. return true;
  78310. };
  78311. /**
  78312. * Translate the bone in local or world space
  78313. * @param vec The amount to translate the bone
  78314. * @param space The space that the translation is in
  78315. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78316. */
  78317. Bone.prototype.translate = function (vec, space, mesh) {
  78318. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78319. var lm = this.getLocalMatrix();
  78320. if (space == BABYLON.Space.LOCAL) {
  78321. lm.m[12] += vec.x;
  78322. lm.m[13] += vec.y;
  78323. lm.m[14] += vec.z;
  78324. }
  78325. else {
  78326. var wm = null;
  78327. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78328. if (mesh) {
  78329. wm = mesh.getWorldMatrix();
  78330. }
  78331. this._skeleton.computeAbsoluteTransforms();
  78332. var tmat = Bone._tmpMats[0];
  78333. var tvec = Bone._tmpVecs[0];
  78334. if (this._parent) {
  78335. if (mesh && wm) {
  78336. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78337. tmat.multiplyToRef(wm, tmat);
  78338. }
  78339. else {
  78340. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78341. }
  78342. }
  78343. tmat.m[12] = 0;
  78344. tmat.m[13] = 0;
  78345. tmat.m[14] = 0;
  78346. tmat.invert();
  78347. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78348. lm.m[12] += tvec.x;
  78349. lm.m[13] += tvec.y;
  78350. lm.m[14] += tvec.z;
  78351. }
  78352. this._markAsDirtyAndDecompose();
  78353. };
  78354. /**
  78355. * Set the postion of the bone in local or world space
  78356. * @param position The position to set the bone
  78357. * @param space The space that the position is in
  78358. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78359. */
  78360. Bone.prototype.setPosition = function (position, space, mesh) {
  78361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78362. var lm = this.getLocalMatrix();
  78363. if (space == BABYLON.Space.LOCAL) {
  78364. lm.m[12] = position.x;
  78365. lm.m[13] = position.y;
  78366. lm.m[14] = position.z;
  78367. }
  78368. else {
  78369. var wm = null;
  78370. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78371. if (mesh) {
  78372. wm = mesh.getWorldMatrix();
  78373. }
  78374. this._skeleton.computeAbsoluteTransforms();
  78375. var tmat = Bone._tmpMats[0];
  78376. var vec = Bone._tmpVecs[0];
  78377. if (this._parent) {
  78378. if (mesh && wm) {
  78379. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78380. tmat.multiplyToRef(wm, tmat);
  78381. }
  78382. else {
  78383. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78384. }
  78385. }
  78386. tmat.invert();
  78387. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78388. lm.m[12] = vec.x;
  78389. lm.m[13] = vec.y;
  78390. lm.m[14] = vec.z;
  78391. }
  78392. this._markAsDirtyAndDecompose();
  78393. };
  78394. /**
  78395. * Set the absolute position of the bone (world space)
  78396. * @param position The position to set the bone
  78397. * @param mesh The mesh that this bone is attached to
  78398. */
  78399. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78400. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78401. };
  78402. /**
  78403. * Scale the bone on the x, y and z axes (in local space)
  78404. * @param x The amount to scale the bone on the x axis
  78405. * @param y The amount to scale the bone on the y axis
  78406. * @param z The amount to scale the bone on the z axis
  78407. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78408. */
  78409. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78410. if (scaleChildren === void 0) { scaleChildren = false; }
  78411. var locMat = this.getLocalMatrix();
  78412. // Apply new scaling on top of current local matrix
  78413. var scaleMat = Bone._tmpMats[0];
  78414. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78415. scaleMat.multiplyToRef(locMat, locMat);
  78416. // Invert scaling matrix and apply the inverse to all children
  78417. scaleMat.invert();
  78418. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78419. var child = _a[_i];
  78420. var cm = child.getLocalMatrix();
  78421. cm.multiplyToRef(scaleMat, cm);
  78422. cm.m[12] *= x;
  78423. cm.m[13] *= y;
  78424. cm.m[14] *= z;
  78425. child._markAsDirtyAndDecompose();
  78426. }
  78427. this._markAsDirtyAndDecompose();
  78428. if (scaleChildren) {
  78429. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78430. var child = _c[_b];
  78431. child.scale(x, y, z, scaleChildren);
  78432. }
  78433. }
  78434. };
  78435. /**
  78436. * Set the bone scaling in local space
  78437. * @param scale defines the scaling vector
  78438. */
  78439. Bone.prototype.setScale = function (scale) {
  78440. this._decompose();
  78441. this._localScaling.copyFrom(scale);
  78442. this._markAsDirtyAndCompose();
  78443. };
  78444. /**
  78445. * Gets the current scaling in local space
  78446. * @returns the current scaling vector
  78447. */
  78448. Bone.prototype.getScale = function () {
  78449. this._decompose();
  78450. return this._localScaling;
  78451. };
  78452. /**
  78453. * Gets the current scaling in local space and stores it in a target vector
  78454. * @param result defines the target vector
  78455. */
  78456. Bone.prototype.getScaleToRef = function (result) {
  78457. this._decompose();
  78458. result.copyFrom(this._localScaling);
  78459. };
  78460. /**
  78461. * Set the yaw, pitch, and roll of the bone in local or world space
  78462. * @param yaw The rotation of the bone on the y axis
  78463. * @param pitch The rotation of the bone on the x axis
  78464. * @param roll The rotation of the bone on the z axis
  78465. * @param space The space that the axes of rotation are in
  78466. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78467. */
  78468. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78470. if (space === BABYLON.Space.LOCAL) {
  78471. var quat = Bone._tmpQuat;
  78472. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78473. this.setRotationQuaternion(quat, space, mesh);
  78474. return;
  78475. }
  78476. var rotMatInv = Bone._tmpMats[0];
  78477. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78478. return;
  78479. }
  78480. var rotMat = Bone._tmpMats[1];
  78481. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78482. rotMatInv.multiplyToRef(rotMat, rotMat);
  78483. this._rotateWithMatrix(rotMat, space, mesh);
  78484. };
  78485. /**
  78486. * Add a rotation to the bone on an axis in local or world space
  78487. * @param axis The axis to rotate the bone on
  78488. * @param amount The amount to rotate the bone
  78489. * @param space The space that the axis is in
  78490. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78491. */
  78492. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78493. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78494. var rmat = Bone._tmpMats[0];
  78495. rmat.m[12] = 0;
  78496. rmat.m[13] = 0;
  78497. rmat.m[14] = 0;
  78498. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78499. this._rotateWithMatrix(rmat, space, mesh);
  78500. };
  78501. /**
  78502. * Set the rotation of the bone to a particular axis angle in local or world space
  78503. * @param axis The axis to rotate the bone on
  78504. * @param angle The angle that the bone should be rotated to
  78505. * @param space The space that the axis is in
  78506. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78507. */
  78508. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78509. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78510. if (space === BABYLON.Space.LOCAL) {
  78511. var quat = Bone._tmpQuat;
  78512. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78513. this.setRotationQuaternion(quat, space, mesh);
  78514. return;
  78515. }
  78516. var rotMatInv = Bone._tmpMats[0];
  78517. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78518. return;
  78519. }
  78520. var rotMat = Bone._tmpMats[1];
  78521. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78522. rotMatInv.multiplyToRef(rotMat, rotMat);
  78523. this._rotateWithMatrix(rotMat, space, mesh);
  78524. };
  78525. /**
  78526. * Set the euler rotation of the bone in local of world space
  78527. * @param rotation The euler rotation that the bone should be set to
  78528. * @param space The space that the rotation is in
  78529. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78530. */
  78531. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78532. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78533. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78534. };
  78535. /**
  78536. * Set the quaternion rotation of the bone in local of world space
  78537. * @param quat The quaternion rotation that the bone should be set to
  78538. * @param space The space that the rotation is in
  78539. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78540. */
  78541. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78542. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78543. if (space === BABYLON.Space.LOCAL) {
  78544. this._decompose();
  78545. this._localRotation.copyFrom(quat);
  78546. this._markAsDirtyAndCompose();
  78547. return;
  78548. }
  78549. var rotMatInv = Bone._tmpMats[0];
  78550. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78551. return;
  78552. }
  78553. var rotMat = Bone._tmpMats[1];
  78554. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78555. rotMatInv.multiplyToRef(rotMat, rotMat);
  78556. this._rotateWithMatrix(rotMat, space, mesh);
  78557. };
  78558. /**
  78559. * Set the rotation matrix of the bone in local of world space
  78560. * @param rotMat The rotation matrix that the bone should be set to
  78561. * @param space The space that the rotation is in
  78562. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78563. */
  78564. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78566. if (space === BABYLON.Space.LOCAL) {
  78567. var quat = Bone._tmpQuat;
  78568. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78569. this.setRotationQuaternion(quat, space, mesh);
  78570. return;
  78571. }
  78572. var rotMatInv = Bone._tmpMats[0];
  78573. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78574. return;
  78575. }
  78576. var rotMat2 = Bone._tmpMats[1];
  78577. rotMat2.copyFrom(rotMat);
  78578. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78579. this._rotateWithMatrix(rotMat2, space, mesh);
  78580. };
  78581. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78583. var lmat = this.getLocalMatrix();
  78584. var lx = lmat.m[12];
  78585. var ly = lmat.m[13];
  78586. var lz = lmat.m[14];
  78587. var parent = this.getParent();
  78588. var parentScale = Bone._tmpMats[3];
  78589. var parentScaleInv = Bone._tmpMats[4];
  78590. if (parent && space == BABYLON.Space.WORLD) {
  78591. if (mesh) {
  78592. parentScale.copyFrom(mesh.getWorldMatrix());
  78593. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78594. }
  78595. else {
  78596. parentScale.copyFrom(parent.getAbsoluteTransform());
  78597. }
  78598. parentScaleInv.copyFrom(parentScale);
  78599. parentScaleInv.invert();
  78600. lmat.multiplyToRef(parentScale, lmat);
  78601. lmat.multiplyToRef(rmat, lmat);
  78602. lmat.multiplyToRef(parentScaleInv, lmat);
  78603. }
  78604. else {
  78605. if (space == BABYLON.Space.WORLD && mesh) {
  78606. parentScale.copyFrom(mesh.getWorldMatrix());
  78607. parentScaleInv.copyFrom(parentScale);
  78608. parentScaleInv.invert();
  78609. lmat.multiplyToRef(parentScale, lmat);
  78610. lmat.multiplyToRef(rmat, lmat);
  78611. lmat.multiplyToRef(parentScaleInv, lmat);
  78612. }
  78613. else {
  78614. lmat.multiplyToRef(rmat, lmat);
  78615. }
  78616. }
  78617. lmat.m[12] = lx;
  78618. lmat.m[13] = ly;
  78619. lmat.m[14] = lz;
  78620. this.computeAbsoluteTransforms();
  78621. this._markAsDirtyAndDecompose();
  78622. };
  78623. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78624. var scaleMatrix = Bone._tmpMats[2];
  78625. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78626. if (mesh) {
  78627. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78628. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78629. }
  78630. rotMatInv.invert();
  78631. if (isNaN(rotMatInv.m[0])) {
  78632. // Matrix failed to invert.
  78633. // This can happen if scale is zero for example.
  78634. return false;
  78635. }
  78636. scaleMatrix.m[0] *= this._scalingDeterminant;
  78637. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78638. return true;
  78639. };
  78640. /**
  78641. * Get the position of the bone in local or world space
  78642. * @param space The space that the returned position is in
  78643. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78644. * @returns The position of the bone
  78645. */
  78646. Bone.prototype.getPosition = function (space, mesh) {
  78647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78648. if (mesh === void 0) { mesh = null; }
  78649. var pos = BABYLON.Vector3.Zero();
  78650. this.getPositionToRef(space, mesh, pos);
  78651. return pos;
  78652. };
  78653. /**
  78654. * Copy the position of the bone to a vector3 in local or world space
  78655. * @param space The space that the returned position is in
  78656. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78657. * @param result The vector3 to copy the position to
  78658. */
  78659. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78661. if (space == BABYLON.Space.LOCAL) {
  78662. var lm = this.getLocalMatrix();
  78663. result.x = lm.m[12];
  78664. result.y = lm.m[13];
  78665. result.z = lm.m[14];
  78666. }
  78667. else {
  78668. var wm = null;
  78669. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78670. if (mesh) {
  78671. wm = mesh.getWorldMatrix();
  78672. }
  78673. this._skeleton.computeAbsoluteTransforms();
  78674. var tmat = Bone._tmpMats[0];
  78675. if (mesh && wm) {
  78676. tmat.copyFrom(this.getAbsoluteTransform());
  78677. tmat.multiplyToRef(wm, tmat);
  78678. }
  78679. else {
  78680. tmat = this.getAbsoluteTransform();
  78681. }
  78682. result.x = tmat.m[12];
  78683. result.y = tmat.m[13];
  78684. result.z = tmat.m[14];
  78685. }
  78686. };
  78687. /**
  78688. * Get the absolute position of the bone (world space)
  78689. * @param mesh The mesh that this bone is attached to
  78690. * @returns The absolute position of the bone
  78691. */
  78692. Bone.prototype.getAbsolutePosition = function (mesh) {
  78693. if (mesh === void 0) { mesh = null; }
  78694. var pos = BABYLON.Vector3.Zero();
  78695. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78696. return pos;
  78697. };
  78698. /**
  78699. * Copy the absolute position of the bone (world space) to the result param
  78700. * @param mesh The mesh that this bone is attached to
  78701. * @param result The vector3 to copy the absolute position to
  78702. */
  78703. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78704. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78705. };
  78706. /**
  78707. * Compute the absolute transforms of this bone and its children
  78708. */
  78709. Bone.prototype.computeAbsoluteTransforms = function () {
  78710. this._compose();
  78711. if (this._parent) {
  78712. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78713. }
  78714. else {
  78715. this._absoluteTransform.copyFrom(this._localMatrix);
  78716. var poseMatrix = this._skeleton.getPoseMatrix();
  78717. if (poseMatrix) {
  78718. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78719. }
  78720. }
  78721. var children = this.children;
  78722. var len = children.length;
  78723. for (var i = 0; i < len; i++) {
  78724. children[i].computeAbsoluteTransforms();
  78725. }
  78726. };
  78727. /**
  78728. * Get the world direction from an axis that is in the local space of the bone
  78729. * @param localAxis The local direction that is used to compute the world direction
  78730. * @param mesh The mesh that this bone is attached to
  78731. * @returns The world direction
  78732. */
  78733. Bone.prototype.getDirection = function (localAxis, mesh) {
  78734. if (mesh === void 0) { mesh = null; }
  78735. var result = BABYLON.Vector3.Zero();
  78736. this.getDirectionToRef(localAxis, mesh, result);
  78737. return result;
  78738. };
  78739. /**
  78740. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78741. * @param localAxis The local direction that is used to compute the world direction
  78742. * @param mesh The mesh that this bone is attached to
  78743. * @param result The vector3 that the world direction will be copied to
  78744. */
  78745. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78746. if (mesh === void 0) { mesh = null; }
  78747. var wm = null;
  78748. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78749. if (mesh) {
  78750. wm = mesh.getWorldMatrix();
  78751. }
  78752. this._skeleton.computeAbsoluteTransforms();
  78753. var mat = Bone._tmpMats[0];
  78754. mat.copyFrom(this.getAbsoluteTransform());
  78755. if (mesh && wm) {
  78756. mat.multiplyToRef(wm, mat);
  78757. }
  78758. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78759. result.normalize();
  78760. };
  78761. /**
  78762. * Get the euler rotation of the bone in local or world space
  78763. * @param space The space that the rotation should be in
  78764. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78765. * @returns The euler rotation
  78766. */
  78767. Bone.prototype.getRotation = function (space, mesh) {
  78768. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78769. if (mesh === void 0) { mesh = null; }
  78770. var result = BABYLON.Vector3.Zero();
  78771. this.getRotationToRef(space, mesh, result);
  78772. return result;
  78773. };
  78774. /**
  78775. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78776. * @param space The space that the rotation should be in
  78777. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78778. * @param result The vector3 that the rotation should be copied to
  78779. */
  78780. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78781. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78782. if (mesh === void 0) { mesh = null; }
  78783. var quat = Bone._tmpQuat;
  78784. this.getRotationQuaternionToRef(space, mesh, quat);
  78785. quat.toEulerAnglesToRef(result);
  78786. };
  78787. /**
  78788. * Get the quaternion rotation of the bone in either local or world space
  78789. * @param space The space that the rotation should be in
  78790. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78791. * @returns The quaternion rotation
  78792. */
  78793. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78794. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78795. if (mesh === void 0) { mesh = null; }
  78796. var result = BABYLON.Quaternion.Identity();
  78797. this.getRotationQuaternionToRef(space, mesh, result);
  78798. return result;
  78799. };
  78800. /**
  78801. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78802. * @param space The space that the rotation should be in
  78803. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78804. * @param result The quaternion that the rotation should be copied to
  78805. */
  78806. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78807. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78808. if (mesh === void 0) { mesh = null; }
  78809. if (space == BABYLON.Space.LOCAL) {
  78810. this._decompose();
  78811. result.copyFrom(this._localRotation);
  78812. }
  78813. else {
  78814. var mat = Bone._tmpMats[0];
  78815. var amat = this.getAbsoluteTransform();
  78816. if (mesh) {
  78817. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78818. }
  78819. else {
  78820. mat.copyFrom(amat);
  78821. }
  78822. mat.m[0] *= this._scalingDeterminant;
  78823. mat.m[1] *= this._scalingDeterminant;
  78824. mat.m[2] *= this._scalingDeterminant;
  78825. mat.decompose(undefined, result, undefined);
  78826. }
  78827. };
  78828. /**
  78829. * Get the rotation matrix of the bone in local or world space
  78830. * @param space The space that the rotation should be in
  78831. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78832. * @returns The rotation matrix
  78833. */
  78834. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78835. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78836. var result = BABYLON.Matrix.Identity();
  78837. this.getRotationMatrixToRef(space, mesh, result);
  78838. return result;
  78839. };
  78840. /**
  78841. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78842. * @param space The space that the rotation should be in
  78843. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78844. * @param result The quaternion that the rotation should be copied to
  78845. */
  78846. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78847. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78848. if (space == BABYLON.Space.LOCAL) {
  78849. this.getLocalMatrix().getRotationMatrixToRef(result);
  78850. }
  78851. else {
  78852. var mat = Bone._tmpMats[0];
  78853. var amat = this.getAbsoluteTransform();
  78854. if (mesh) {
  78855. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78856. }
  78857. else {
  78858. mat.copyFrom(amat);
  78859. }
  78860. mat.m[0] *= this._scalingDeterminant;
  78861. mat.m[1] *= this._scalingDeterminant;
  78862. mat.m[2] *= this._scalingDeterminant;
  78863. mat.getRotationMatrixToRef(result);
  78864. }
  78865. };
  78866. /**
  78867. * Get the world position of a point that is in the local space of the bone
  78868. * @param position The local position
  78869. * @param mesh The mesh that this bone is attached to
  78870. * @returns The world position
  78871. */
  78872. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78873. if (mesh === void 0) { mesh = null; }
  78874. var result = BABYLON.Vector3.Zero();
  78875. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78876. return result;
  78877. };
  78878. /**
  78879. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78880. * @param position The local position
  78881. * @param mesh The mesh that this bone is attached to
  78882. * @param result The vector3 that the world position should be copied to
  78883. */
  78884. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78885. if (mesh === void 0) { mesh = null; }
  78886. var wm = null;
  78887. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78888. if (mesh) {
  78889. wm = mesh.getWorldMatrix();
  78890. }
  78891. this._skeleton.computeAbsoluteTransforms();
  78892. var tmat = Bone._tmpMats[0];
  78893. if (mesh && wm) {
  78894. tmat.copyFrom(this.getAbsoluteTransform());
  78895. tmat.multiplyToRef(wm, tmat);
  78896. }
  78897. else {
  78898. tmat = this.getAbsoluteTransform();
  78899. }
  78900. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78901. };
  78902. /**
  78903. * Get the local position of a point that is in world space
  78904. * @param position The world position
  78905. * @param mesh The mesh that this bone is attached to
  78906. * @returns The local position
  78907. */
  78908. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78909. if (mesh === void 0) { mesh = null; }
  78910. var result = BABYLON.Vector3.Zero();
  78911. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78912. return result;
  78913. };
  78914. /**
  78915. * Get the local position of a point that is in world space and copy it to the result param
  78916. * @param position The world position
  78917. * @param mesh The mesh that this bone is attached to
  78918. * @param result The vector3 that the local position should be copied to
  78919. */
  78920. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78921. if (mesh === void 0) { mesh = null; }
  78922. var wm = null;
  78923. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78924. if (mesh) {
  78925. wm = mesh.getWorldMatrix();
  78926. }
  78927. this._skeleton.computeAbsoluteTransforms();
  78928. var tmat = Bone._tmpMats[0];
  78929. tmat.copyFrom(this.getAbsoluteTransform());
  78930. if (mesh && wm) {
  78931. tmat.multiplyToRef(wm, tmat);
  78932. }
  78933. tmat.invert();
  78934. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78935. };
  78936. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78937. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78938. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78939. return Bone;
  78940. }(BABYLON.Node));
  78941. BABYLON.Bone = Bone;
  78942. })(BABYLON || (BABYLON = {}));
  78943. //# sourceMappingURL=babylon.bone.js.map
  78944. var BABYLON;
  78945. (function (BABYLON) {
  78946. /**
  78947. * Class used to apply inverse kinematics to bones
  78948. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78949. */
  78950. var BoneIKController = /** @class */ (function () {
  78951. /**
  78952. * Creates a new BoneIKController
  78953. * @param mesh defines the mesh to control
  78954. * @param bone defines the bone to control
  78955. * @param options defines options to set up the controller
  78956. */
  78957. function BoneIKController(mesh, bone, options) {
  78958. /**
  78959. * Gets or sets the target position
  78960. */
  78961. this.targetPosition = BABYLON.Vector3.Zero();
  78962. /**
  78963. * Gets or sets the pole target position
  78964. */
  78965. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78966. /**
  78967. * Gets or sets the pole target local offset
  78968. */
  78969. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78970. /**
  78971. * Gets or sets the pole angle
  78972. */
  78973. this.poleAngle = 0;
  78974. /**
  78975. * 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)
  78976. */
  78977. this.slerpAmount = 1;
  78978. this._bone1Quat = BABYLON.Quaternion.Identity();
  78979. this._bone1Mat = BABYLON.Matrix.Identity();
  78980. this._bone2Ang = Math.PI;
  78981. this._maxAngle = Math.PI;
  78982. this._rightHandedSystem = false;
  78983. this._bendAxis = BABYLON.Vector3.Right();
  78984. this._slerping = false;
  78985. this._adjustRoll = 0;
  78986. this._bone2 = bone;
  78987. this._bone1 = bone.getParent();
  78988. if (!this._bone1) {
  78989. return;
  78990. }
  78991. this.mesh = mesh;
  78992. var bonePos = bone.getPosition();
  78993. if (bone.getAbsoluteTransform().determinant() > 0) {
  78994. this._rightHandedSystem = true;
  78995. this._bendAxis.x = 0;
  78996. this._bendAxis.y = 0;
  78997. this._bendAxis.z = -1;
  78998. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78999. this._adjustRoll = Math.PI * .5;
  79000. this._bendAxis.z = 1;
  79001. }
  79002. }
  79003. if (this._bone1.length) {
  79004. var boneScale1 = this._bone1.getScale();
  79005. var boneScale2 = this._bone2.getScale();
  79006. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79007. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79008. }
  79009. else if (this._bone1.children[0]) {
  79010. mesh.computeWorldMatrix(true);
  79011. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79012. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79013. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79014. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79015. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79016. }
  79017. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79018. this.maxAngle = Math.PI;
  79019. if (options) {
  79020. if (options.targetMesh) {
  79021. this.targetMesh = options.targetMesh;
  79022. this.targetMesh.computeWorldMatrix(true);
  79023. }
  79024. if (options.poleTargetMesh) {
  79025. this.poleTargetMesh = options.poleTargetMesh;
  79026. this.poleTargetMesh.computeWorldMatrix(true);
  79027. }
  79028. else if (options.poleTargetBone) {
  79029. this.poleTargetBone = options.poleTargetBone;
  79030. }
  79031. else if (this._bone1.getParent()) {
  79032. this.poleTargetBone = this._bone1.getParent();
  79033. }
  79034. if (options.poleTargetLocalOffset) {
  79035. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79036. }
  79037. if (options.poleAngle) {
  79038. this.poleAngle = options.poleAngle;
  79039. }
  79040. if (options.bendAxis) {
  79041. this._bendAxis.copyFrom(options.bendAxis);
  79042. }
  79043. if (options.maxAngle) {
  79044. this.maxAngle = options.maxAngle;
  79045. }
  79046. if (options.slerpAmount) {
  79047. this.slerpAmount = options.slerpAmount;
  79048. }
  79049. }
  79050. }
  79051. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79052. /**
  79053. * Gets or sets maximum allowed angle
  79054. */
  79055. get: function () {
  79056. return this._maxAngle;
  79057. },
  79058. set: function (value) {
  79059. this._setMaxAngle(value);
  79060. },
  79061. enumerable: true,
  79062. configurable: true
  79063. });
  79064. BoneIKController.prototype._setMaxAngle = function (ang) {
  79065. if (ang < 0) {
  79066. ang = 0;
  79067. }
  79068. if (ang > Math.PI || ang == undefined) {
  79069. ang = Math.PI;
  79070. }
  79071. this._maxAngle = ang;
  79072. var a = this._bone1Length;
  79073. var b = this._bone2Length;
  79074. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79075. };
  79076. /**
  79077. * Force the controller to update the bones
  79078. */
  79079. BoneIKController.prototype.update = function () {
  79080. var bone1 = this._bone1;
  79081. if (!bone1) {
  79082. return;
  79083. }
  79084. var target = this.targetPosition;
  79085. var poleTarget = this.poleTargetPosition;
  79086. var mat1 = BoneIKController._tmpMats[0];
  79087. var mat2 = BoneIKController._tmpMats[1];
  79088. if (this.targetMesh) {
  79089. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79090. }
  79091. if (this.poleTargetBone) {
  79092. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79093. }
  79094. else if (this.poleTargetMesh) {
  79095. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79096. }
  79097. var bonePos = BoneIKController._tmpVecs[0];
  79098. var zaxis = BoneIKController._tmpVecs[1];
  79099. var xaxis = BoneIKController._tmpVecs[2];
  79100. var yaxis = BoneIKController._tmpVecs[3];
  79101. var upAxis = BoneIKController._tmpVecs[4];
  79102. var _tmpQuat = BoneIKController._tmpQuat;
  79103. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79104. poleTarget.subtractToRef(bonePos, upAxis);
  79105. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79106. upAxis.y = 1;
  79107. }
  79108. else {
  79109. upAxis.normalize();
  79110. }
  79111. target.subtractToRef(bonePos, yaxis);
  79112. yaxis.normalize();
  79113. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79114. zaxis.normalize();
  79115. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79116. xaxis.normalize();
  79117. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79118. var a = this._bone1Length;
  79119. var b = this._bone2Length;
  79120. var c = BABYLON.Vector3.Distance(bonePos, target);
  79121. if (this._maxReach > 0) {
  79122. c = Math.min(this._maxReach, c);
  79123. }
  79124. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79125. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79126. if (acosa > 1) {
  79127. acosa = 1;
  79128. }
  79129. if (acosb > 1) {
  79130. acosb = 1;
  79131. }
  79132. if (acosa < -1) {
  79133. acosa = -1;
  79134. }
  79135. if (acosb < -1) {
  79136. acosb = -1;
  79137. }
  79138. var angA = Math.acos(acosa);
  79139. var angB = Math.acos(acosb);
  79140. var angC = -angA - angB;
  79141. if (this._rightHandedSystem) {
  79142. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79143. mat2.multiplyToRef(mat1, mat1);
  79144. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79145. mat2.multiplyToRef(mat1, mat1);
  79146. }
  79147. else {
  79148. var _tmpVec = BoneIKController._tmpVecs[5];
  79149. _tmpVec.copyFrom(this._bendAxis);
  79150. _tmpVec.x *= -1;
  79151. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79152. mat2.multiplyToRef(mat1, mat1);
  79153. }
  79154. if (this.poleAngle) {
  79155. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79156. mat1.multiplyToRef(mat2, mat1);
  79157. }
  79158. if (this._bone1) {
  79159. if (this.slerpAmount < 1) {
  79160. if (!this._slerping) {
  79161. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79162. }
  79163. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79164. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79165. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79166. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79167. this._slerping = true;
  79168. }
  79169. else {
  79170. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79171. this._bone1Mat.copyFrom(mat1);
  79172. this._slerping = false;
  79173. }
  79174. }
  79175. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79176. this._bone2Ang = angC;
  79177. };
  79178. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79179. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79180. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79181. return BoneIKController;
  79182. }());
  79183. BABYLON.BoneIKController = BoneIKController;
  79184. })(BABYLON || (BABYLON = {}));
  79185. //# sourceMappingURL=babylon.boneIKController.js.map
  79186. var BABYLON;
  79187. (function (BABYLON) {
  79188. /**
  79189. * Class used to make a bone look toward a point in space
  79190. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79191. */
  79192. var BoneLookController = /** @class */ (function () {
  79193. /**
  79194. * Create a BoneLookController
  79195. * @param mesh the mesh that the bone belongs to
  79196. * @param bone the bone that will be looking to the target
  79197. * @param target the target Vector3 to look at
  79198. * @param settings optional settings:
  79199. * * maxYaw: the maximum angle the bone will yaw to
  79200. * * minYaw: the minimum angle the bone will yaw to
  79201. * * maxPitch: the maximum angle the bone will pitch to
  79202. * * minPitch: the minimum angle the bone will yaw to
  79203. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79204. * * upAxis: the up axis of the coordinate system
  79205. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79206. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79207. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79208. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79209. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79210. * * adjustRoll: used to make an adjustment to the roll of the bone
  79211. **/
  79212. function BoneLookController(mesh, bone, target, options) {
  79213. /**
  79214. * The up axis of the coordinate system that is used when the bone is rotated
  79215. */
  79216. this.upAxis = BABYLON.Vector3.Up();
  79217. /**
  79218. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79219. */
  79220. this.upAxisSpace = BABYLON.Space.LOCAL;
  79221. /**
  79222. * Used to make an adjustment to the yaw of the bone
  79223. */
  79224. this.adjustYaw = 0;
  79225. /**
  79226. * Used to make an adjustment to the pitch of the bone
  79227. */
  79228. this.adjustPitch = 0;
  79229. /**
  79230. * Used to make an adjustment to the roll of the bone
  79231. */
  79232. this.adjustRoll = 0;
  79233. /**
  79234. * 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)
  79235. */
  79236. this.slerpAmount = 1;
  79237. this._boneQuat = BABYLON.Quaternion.Identity();
  79238. this._slerping = false;
  79239. this._firstFrameSkipped = false;
  79240. this._fowardAxis = BABYLON.Vector3.Forward();
  79241. this.mesh = mesh;
  79242. this.bone = bone;
  79243. this.target = target;
  79244. if (options) {
  79245. if (options.adjustYaw) {
  79246. this.adjustYaw = options.adjustYaw;
  79247. }
  79248. if (options.adjustPitch) {
  79249. this.adjustPitch = options.adjustPitch;
  79250. }
  79251. if (options.adjustRoll) {
  79252. this.adjustRoll = options.adjustRoll;
  79253. }
  79254. if (options.maxYaw != null) {
  79255. this.maxYaw = options.maxYaw;
  79256. }
  79257. else {
  79258. this.maxYaw = Math.PI;
  79259. }
  79260. if (options.minYaw != null) {
  79261. this.minYaw = options.minYaw;
  79262. }
  79263. else {
  79264. this.minYaw = -Math.PI;
  79265. }
  79266. if (options.maxPitch != null) {
  79267. this.maxPitch = options.maxPitch;
  79268. }
  79269. else {
  79270. this.maxPitch = Math.PI;
  79271. }
  79272. if (options.minPitch != null) {
  79273. this.minPitch = options.minPitch;
  79274. }
  79275. else {
  79276. this.minPitch = -Math.PI;
  79277. }
  79278. if (options.slerpAmount != null) {
  79279. this.slerpAmount = options.slerpAmount;
  79280. }
  79281. if (options.upAxis != null) {
  79282. this.upAxis = options.upAxis;
  79283. }
  79284. if (options.upAxisSpace != null) {
  79285. this.upAxisSpace = options.upAxisSpace;
  79286. }
  79287. if (options.yawAxis != null || options.pitchAxis != null) {
  79288. var newYawAxis = BABYLON.Axis.Y;
  79289. var newPitchAxis = BABYLON.Axis.X;
  79290. if (options.yawAxis != null) {
  79291. newYawAxis = options.yawAxis.clone();
  79292. newYawAxis.normalize();
  79293. }
  79294. if (options.pitchAxis != null) {
  79295. newPitchAxis = options.pitchAxis.clone();
  79296. newPitchAxis.normalize();
  79297. }
  79298. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79299. this._transformYawPitch = BABYLON.Matrix.Identity();
  79300. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79301. this._transformYawPitchInv = this._transformYawPitch.clone();
  79302. this._transformYawPitch.invert();
  79303. }
  79304. }
  79305. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79306. this.upAxisSpace = BABYLON.Space.LOCAL;
  79307. }
  79308. }
  79309. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79310. /**
  79311. * Gets or sets the minimum yaw angle that the bone can look to
  79312. */
  79313. get: function () {
  79314. return this._minYaw;
  79315. },
  79316. set: function (value) {
  79317. this._minYaw = value;
  79318. this._minYawSin = Math.sin(value);
  79319. this._minYawCos = Math.cos(value);
  79320. if (this._maxYaw != null) {
  79321. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79322. this._yawRange = this._maxYaw - this._minYaw;
  79323. }
  79324. },
  79325. enumerable: true,
  79326. configurable: true
  79327. });
  79328. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79329. /**
  79330. * Gets or sets the maximum yaw angle that the bone can look to
  79331. */
  79332. get: function () {
  79333. return this._maxYaw;
  79334. },
  79335. set: function (value) {
  79336. this._maxYaw = value;
  79337. this._maxYawSin = Math.sin(value);
  79338. this._maxYawCos = Math.cos(value);
  79339. if (this._minYaw != null) {
  79340. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79341. this._yawRange = this._maxYaw - this._minYaw;
  79342. }
  79343. },
  79344. enumerable: true,
  79345. configurable: true
  79346. });
  79347. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79348. /**
  79349. * Gets or sets the minimum pitch angle that the bone can look to
  79350. */
  79351. get: function () {
  79352. return this._minPitch;
  79353. },
  79354. set: function (value) {
  79355. this._minPitch = value;
  79356. this._minPitchTan = Math.tan(value);
  79357. },
  79358. enumerable: true,
  79359. configurable: true
  79360. });
  79361. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79362. /**
  79363. * Gets or sets the maximum pitch angle that the bone can look to
  79364. */
  79365. get: function () {
  79366. return this._maxPitch;
  79367. },
  79368. set: function (value) {
  79369. this._maxPitch = value;
  79370. this._maxPitchTan = Math.tan(value);
  79371. },
  79372. enumerable: true,
  79373. configurable: true
  79374. });
  79375. /**
  79376. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79377. */
  79378. BoneLookController.prototype.update = function () {
  79379. //skip the first frame when slerping so that the mesh rotation is correct
  79380. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79381. this._firstFrameSkipped = true;
  79382. return;
  79383. }
  79384. var bone = this.bone;
  79385. var bonePos = BoneLookController._tmpVecs[0];
  79386. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79387. var target = this.target;
  79388. var _tmpMat1 = BoneLookController._tmpMats[0];
  79389. var _tmpMat2 = BoneLookController._tmpMats[1];
  79390. var mesh = this.mesh;
  79391. var parentBone = bone.getParent();
  79392. var upAxis = BoneLookController._tmpVecs[1];
  79393. upAxis.copyFrom(this.upAxis);
  79394. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79395. if (this._transformYawPitch) {
  79396. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79397. }
  79398. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79399. }
  79400. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79401. mesh.getDirectionToRef(upAxis, upAxis);
  79402. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79403. upAxis.normalize();
  79404. }
  79405. }
  79406. var checkYaw = false;
  79407. var checkPitch = false;
  79408. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79409. checkYaw = true;
  79410. }
  79411. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79412. checkPitch = true;
  79413. }
  79414. if (checkYaw || checkPitch) {
  79415. var spaceMat = BoneLookController._tmpMats[2];
  79416. var spaceMatInv = BoneLookController._tmpMats[3];
  79417. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79418. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79419. }
  79420. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79421. spaceMat.copyFrom(mesh.getWorldMatrix());
  79422. }
  79423. else {
  79424. var forwardAxis = BoneLookController._tmpVecs[2];
  79425. forwardAxis.copyFrom(this._fowardAxis);
  79426. if (this._transformYawPitch) {
  79427. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79428. }
  79429. if (parentBone) {
  79430. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79431. }
  79432. else {
  79433. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79434. }
  79435. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79436. rightAxis.normalize();
  79437. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79438. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79439. }
  79440. spaceMat.invertToRef(spaceMatInv);
  79441. var xzlen = null;
  79442. if (checkPitch) {
  79443. var localTarget = BoneLookController._tmpVecs[3];
  79444. target.subtractToRef(bonePos, localTarget);
  79445. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79446. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79447. var pitch = Math.atan2(localTarget.y, xzlen);
  79448. var newPitch = pitch;
  79449. if (pitch > this._maxPitch) {
  79450. localTarget.y = this._maxPitchTan * xzlen;
  79451. newPitch = this._maxPitch;
  79452. }
  79453. else if (pitch < this._minPitch) {
  79454. localTarget.y = this._minPitchTan * xzlen;
  79455. newPitch = this._minPitch;
  79456. }
  79457. if (pitch != newPitch) {
  79458. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79459. localTarget.addInPlace(bonePos);
  79460. target = localTarget;
  79461. }
  79462. }
  79463. if (checkYaw) {
  79464. var localTarget = BoneLookController._tmpVecs[4];
  79465. target.subtractToRef(bonePos, localTarget);
  79466. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79467. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79468. var newYaw = yaw;
  79469. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79470. if (xzlen == null) {
  79471. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79472. }
  79473. if (this._yawRange > Math.PI) {
  79474. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79475. localTarget.z = this._maxYawCos * xzlen;
  79476. localTarget.x = this._maxYawSin * xzlen;
  79477. newYaw = this._maxYaw;
  79478. }
  79479. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79480. localTarget.z = this._minYawCos * xzlen;
  79481. localTarget.x = this._minYawSin * xzlen;
  79482. newYaw = this._minYaw;
  79483. }
  79484. }
  79485. else {
  79486. if (yaw > this._maxYaw) {
  79487. localTarget.z = this._maxYawCos * xzlen;
  79488. localTarget.x = this._maxYawSin * xzlen;
  79489. newYaw = this._maxYaw;
  79490. }
  79491. else if (yaw < this._minYaw) {
  79492. localTarget.z = this._minYawCos * xzlen;
  79493. localTarget.x = this._minYawSin * xzlen;
  79494. newYaw = this._minYaw;
  79495. }
  79496. }
  79497. }
  79498. if (this._slerping && this._yawRange > Math.PI) {
  79499. //are we going to be crossing into the min/max region?
  79500. var boneFwd = BoneLookController._tmpVecs[8];
  79501. boneFwd.copyFrom(BABYLON.Axis.Z);
  79502. if (this._transformYawPitch) {
  79503. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79504. }
  79505. var boneRotMat = BoneLookController._tmpMats[4];
  79506. this._boneQuat.toRotationMatrix(boneRotMat);
  79507. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79508. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79509. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79510. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79511. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79512. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79513. if (angBtwTar > angBtwMidYaw) {
  79514. if (xzlen == null) {
  79515. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79516. }
  79517. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79518. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79519. if (angBtwMin < angBtwMax) {
  79520. newYaw = boneYaw + Math.PI * .75;
  79521. localTarget.z = Math.cos(newYaw) * xzlen;
  79522. localTarget.x = Math.sin(newYaw) * xzlen;
  79523. }
  79524. else {
  79525. newYaw = boneYaw - Math.PI * .75;
  79526. localTarget.z = Math.cos(newYaw) * xzlen;
  79527. localTarget.x = Math.sin(newYaw) * xzlen;
  79528. }
  79529. }
  79530. }
  79531. if (yaw != newYaw) {
  79532. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79533. localTarget.addInPlace(bonePos);
  79534. target = localTarget;
  79535. }
  79536. }
  79537. }
  79538. var zaxis = BoneLookController._tmpVecs[5];
  79539. var xaxis = BoneLookController._tmpVecs[6];
  79540. var yaxis = BoneLookController._tmpVecs[7];
  79541. var _tmpQuat = BoneLookController._tmpQuat;
  79542. target.subtractToRef(bonePos, zaxis);
  79543. zaxis.normalize();
  79544. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79545. xaxis.normalize();
  79546. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79547. yaxis.normalize();
  79548. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79549. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79550. return;
  79551. }
  79552. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79553. return;
  79554. }
  79555. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79556. return;
  79557. }
  79558. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79559. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79560. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79561. }
  79562. if (this.slerpAmount < 1) {
  79563. if (!this._slerping) {
  79564. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79565. }
  79566. if (this._transformYawPitch) {
  79567. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79568. }
  79569. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79570. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79571. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79572. this._slerping = true;
  79573. }
  79574. else {
  79575. if (this._transformYawPitch) {
  79576. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79577. }
  79578. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79579. this._slerping = false;
  79580. }
  79581. };
  79582. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79583. var angDiff = ang2 - ang1;
  79584. angDiff %= Math.PI * 2;
  79585. if (angDiff > Math.PI) {
  79586. angDiff -= Math.PI * 2;
  79587. }
  79588. else if (angDiff < -Math.PI) {
  79589. angDiff += Math.PI * 2;
  79590. }
  79591. return angDiff;
  79592. };
  79593. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79594. ang1 %= (2 * Math.PI);
  79595. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79596. ang2 %= (2 * Math.PI);
  79597. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79598. var ab = 0;
  79599. if (ang1 < ang2) {
  79600. ab = ang2 - ang1;
  79601. }
  79602. else {
  79603. ab = ang1 - ang2;
  79604. }
  79605. if (ab > Math.PI) {
  79606. ab = Math.PI * 2 - ab;
  79607. }
  79608. return ab;
  79609. };
  79610. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79611. ang %= (2 * Math.PI);
  79612. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79613. ang1 %= (2 * Math.PI);
  79614. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79615. ang2 %= (2 * Math.PI);
  79616. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79617. if (ang1 < ang2) {
  79618. if (ang > ang1 && ang < ang2) {
  79619. return true;
  79620. }
  79621. }
  79622. else {
  79623. if (ang > ang2 && ang < ang1) {
  79624. return true;
  79625. }
  79626. }
  79627. return false;
  79628. };
  79629. 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()];
  79630. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79631. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79632. return BoneLookController;
  79633. }());
  79634. BABYLON.BoneLookController = BoneLookController;
  79635. })(BABYLON || (BABYLON = {}));
  79636. //# sourceMappingURL=babylon.boneLookController.js.map
  79637. var BABYLON;
  79638. (function (BABYLON) {
  79639. /**
  79640. * Class used to handle skinning animations
  79641. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79642. */
  79643. var Skeleton = /** @class */ (function () {
  79644. /**
  79645. * Creates a new skeleton
  79646. * @param name defines the skeleton name
  79647. * @param id defines the skeleton Id
  79648. * @param scene defines the hosting scene
  79649. */
  79650. function Skeleton(
  79651. /** defines the skeleton name */
  79652. name,
  79653. /** defines the skeleton Id */
  79654. id, scene) {
  79655. this.name = name;
  79656. this.id = id;
  79657. /**
  79658. * Gets the list of child bones
  79659. */
  79660. this.bones = new Array();
  79661. /**
  79662. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79663. */
  79664. this.needInitialSkinMatrix = false;
  79665. this._isDirty = true;
  79666. this._meshesWithPoseMatrix = new Array();
  79667. this._identity = BABYLON.Matrix.Identity();
  79668. this._ranges = {};
  79669. this._lastAbsoluteTransformsUpdateId = -1;
  79670. /**
  79671. * Specifies if the skeleton should be serialized
  79672. */
  79673. this.doNotSerialize = false;
  79674. this._animationPropertiesOverride = null;
  79675. // Events
  79676. /**
  79677. * An observable triggered before computing the skeleton's matrices
  79678. */
  79679. this.onBeforeComputeObservable = new BABYLON.Observable();
  79680. this.bones = [];
  79681. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79682. scene.skeletons.push(this);
  79683. //make sure it will recalculate the matrix next time prepare is called.
  79684. this._isDirty = true;
  79685. }
  79686. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79687. /**
  79688. * Gets or sets the animation properties override
  79689. */
  79690. get: function () {
  79691. if (!this._animationPropertiesOverride) {
  79692. return this._scene.animationPropertiesOverride;
  79693. }
  79694. return this._animationPropertiesOverride;
  79695. },
  79696. set: function (value) {
  79697. this._animationPropertiesOverride = value;
  79698. },
  79699. enumerable: true,
  79700. configurable: true
  79701. });
  79702. // Members
  79703. /**
  79704. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79705. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79706. * @returns a Float32Array containing matrices data
  79707. */
  79708. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79709. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79710. return mesh._bonesTransformMatrices;
  79711. }
  79712. if (!this._transformMatrices) {
  79713. this.prepare();
  79714. }
  79715. return this._transformMatrices;
  79716. };
  79717. /**
  79718. * Gets the current hosting scene
  79719. * @returns a scene object
  79720. */
  79721. Skeleton.prototype.getScene = function () {
  79722. return this._scene;
  79723. };
  79724. // Methods
  79725. /**
  79726. * Gets a string representing the current skeleton data
  79727. * @param fullDetails defines a boolean indicating if we want a verbose version
  79728. * @returns a string representing the current skeleton data
  79729. */
  79730. Skeleton.prototype.toString = function (fullDetails) {
  79731. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79732. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79733. if (fullDetails) {
  79734. ret += ", Ranges: {";
  79735. var first = true;
  79736. for (var name_1 in this._ranges) {
  79737. if (first) {
  79738. ret += ", ";
  79739. first = false;
  79740. }
  79741. ret += name_1;
  79742. }
  79743. ret += "}";
  79744. }
  79745. return ret;
  79746. };
  79747. /**
  79748. * Get bone's index searching by name
  79749. * @param name defines bone's name to search for
  79750. * @return the indice of the bone. Returns -1 if not found
  79751. */
  79752. Skeleton.prototype.getBoneIndexByName = function (name) {
  79753. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79754. if (this.bones[boneIndex].name === name) {
  79755. return boneIndex;
  79756. }
  79757. }
  79758. return -1;
  79759. };
  79760. /**
  79761. * Creater a new animation range
  79762. * @param name defines the name of the range
  79763. * @param from defines the start key
  79764. * @param to defines the end key
  79765. */
  79766. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79767. // check name not already in use
  79768. if (!this._ranges[name]) {
  79769. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79770. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79771. if (this.bones[i].animations[0]) {
  79772. this.bones[i].animations[0].createRange(name, from, to);
  79773. }
  79774. }
  79775. }
  79776. };
  79777. /**
  79778. * Delete a specific animation range
  79779. * @param name defines the name of the range
  79780. * @param deleteFrames defines if frames must be removed as well
  79781. */
  79782. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79783. if (deleteFrames === void 0) { deleteFrames = true; }
  79784. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79785. if (this.bones[i].animations[0]) {
  79786. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79787. }
  79788. }
  79789. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79790. };
  79791. /**
  79792. * Gets a specific animation range
  79793. * @param name defines the name of the range to look for
  79794. * @returns the requested animation range or null if not found
  79795. */
  79796. Skeleton.prototype.getAnimationRange = function (name) {
  79797. return this._ranges[name];
  79798. };
  79799. /**
  79800. * Gets the list of all animation ranges defined on this skeleton
  79801. * @returns an array
  79802. */
  79803. Skeleton.prototype.getAnimationRanges = function () {
  79804. var animationRanges = [];
  79805. var name;
  79806. var i = 0;
  79807. for (name in this._ranges) {
  79808. animationRanges[i] = this._ranges[name];
  79809. i++;
  79810. }
  79811. return animationRanges;
  79812. };
  79813. /**
  79814. * Copy animation range from a source skeleton.
  79815. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79816. * @param source defines the source skeleton
  79817. * @param name defines the name of the range to copy
  79818. * @param rescaleAsRequired defines if rescaling must be applied if required
  79819. * @returns true if operation was successful
  79820. */
  79821. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79822. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79823. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79824. return false;
  79825. }
  79826. var ret = true;
  79827. var frameOffset = this._getHighestAnimationFrame() + 1;
  79828. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79829. var boneDict = {};
  79830. var sourceBones = source.bones;
  79831. var nBones;
  79832. var i;
  79833. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79834. boneDict[sourceBones[i].name] = sourceBones[i];
  79835. }
  79836. if (this.bones.length !== sourceBones.length) {
  79837. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79838. ret = false;
  79839. }
  79840. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79841. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79842. var boneName = this.bones[i].name;
  79843. var sourceBone = boneDict[boneName];
  79844. if (sourceBone) {
  79845. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79846. }
  79847. else {
  79848. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79849. ret = false;
  79850. }
  79851. }
  79852. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79853. var range = source.getAnimationRange(name);
  79854. if (range) {
  79855. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79856. }
  79857. return ret;
  79858. };
  79859. /**
  79860. * Forces the skeleton to go to rest pose
  79861. */
  79862. Skeleton.prototype.returnToRest = function () {
  79863. for (var index = 0; index < this.bones.length; index++) {
  79864. this.bones[index].returnToRest();
  79865. }
  79866. };
  79867. Skeleton.prototype._getHighestAnimationFrame = function () {
  79868. var ret = 0;
  79869. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79870. if (this.bones[i].animations[0]) {
  79871. var highest = this.bones[i].animations[0].getHighestFrame();
  79872. if (ret < highest) {
  79873. ret = highest;
  79874. }
  79875. }
  79876. }
  79877. return ret;
  79878. };
  79879. /**
  79880. * Begin a specific animation range
  79881. * @param name defines the name of the range to start
  79882. * @param loop defines if looping must be turned on (false by default)
  79883. * @param speedRatio defines the speed ratio to apply (1 by default)
  79884. * @param onAnimationEnd defines a callback which will be called when animation will end
  79885. * @returns a new animatable
  79886. */
  79887. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79888. var range = this.getAnimationRange(name);
  79889. if (!range) {
  79890. return null;
  79891. }
  79892. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79893. };
  79894. /** @hidden */
  79895. Skeleton.prototype._markAsDirty = function () {
  79896. this._isDirty = true;
  79897. };
  79898. /** @hidden */
  79899. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79900. this._meshesWithPoseMatrix.push(mesh);
  79901. };
  79902. /** @hidden */
  79903. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79904. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79905. if (index > -1) {
  79906. this._meshesWithPoseMatrix.splice(index, 1);
  79907. }
  79908. };
  79909. /** @hidden */
  79910. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79911. this.onBeforeComputeObservable.notifyObservers(this);
  79912. for (var index = 0; index < this.bones.length; index++) {
  79913. var bone = this.bones[index];
  79914. var parentBone = bone.getParent();
  79915. if (parentBone) {
  79916. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79917. }
  79918. else {
  79919. if (initialSkinMatrix) {
  79920. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79921. }
  79922. else {
  79923. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79924. }
  79925. }
  79926. if (bone._index !== -1) {
  79927. var mappedIndex = bone._index === null ? index : bone._index;
  79928. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79929. }
  79930. }
  79931. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79932. };
  79933. /**
  79934. * Build all resources required to render a skeleton
  79935. */
  79936. Skeleton.prototype.prepare = function () {
  79937. if (!this._isDirty) {
  79938. return;
  79939. }
  79940. if (this.needInitialSkinMatrix) {
  79941. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79942. var mesh = this._meshesWithPoseMatrix[index];
  79943. var poseMatrix = mesh.getPoseMatrix();
  79944. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79945. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79946. }
  79947. if (this._synchronizedWithMesh !== mesh) {
  79948. this._synchronizedWithMesh = mesh;
  79949. // Prepare bones
  79950. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79951. var bone = this.bones[boneIndex];
  79952. if (!bone.getParent()) {
  79953. var matrix = bone.getBaseMatrix();
  79954. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79955. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79956. }
  79957. }
  79958. }
  79959. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79960. }
  79961. }
  79962. else {
  79963. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79964. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79965. }
  79966. this._computeTransformMatrices(this._transformMatrices, null);
  79967. }
  79968. this._isDirty = false;
  79969. this._scene._activeBones.addCount(this.bones.length, false);
  79970. };
  79971. /**
  79972. * Gets the list of animatables currently running for this skeleton
  79973. * @returns an array of animatables
  79974. */
  79975. Skeleton.prototype.getAnimatables = function () {
  79976. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79977. this._animatables = [];
  79978. for (var index = 0; index < this.bones.length; index++) {
  79979. this._animatables.push(this.bones[index]);
  79980. }
  79981. }
  79982. return this._animatables;
  79983. };
  79984. /**
  79985. * Clone the current skeleton
  79986. * @param name defines the name of the new skeleton
  79987. * @param id defines the id of the enw skeleton
  79988. * @returns the new skeleton
  79989. */
  79990. Skeleton.prototype.clone = function (name, id) {
  79991. var result = new Skeleton(name, id || name, this._scene);
  79992. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79993. for (var index = 0; index < this.bones.length; index++) {
  79994. var source = this.bones[index];
  79995. var parentBone = null;
  79996. var parent_1 = source.getParent();
  79997. if (parent_1) {
  79998. var parentIndex = this.bones.indexOf(parent_1);
  79999. parentBone = result.bones[parentIndex];
  80000. }
  80001. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80002. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80003. }
  80004. if (this._ranges) {
  80005. result._ranges = {};
  80006. for (var rangeName in this._ranges) {
  80007. var range = this._ranges[rangeName];
  80008. if (range) {
  80009. result._ranges[rangeName] = range.clone();
  80010. }
  80011. }
  80012. }
  80013. this._isDirty = true;
  80014. return result;
  80015. };
  80016. /**
  80017. * Enable animation blending for this skeleton
  80018. * @param blendingSpeed defines the blending speed to apply
  80019. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80020. */
  80021. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80022. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80023. this.bones.forEach(function (bone) {
  80024. bone.animations.forEach(function (animation) {
  80025. animation.enableBlending = true;
  80026. animation.blendingSpeed = blendingSpeed;
  80027. });
  80028. });
  80029. };
  80030. /**
  80031. * Releases all resources associated with the current skeleton
  80032. */
  80033. Skeleton.prototype.dispose = function () {
  80034. this._meshesWithPoseMatrix = [];
  80035. // Animations
  80036. this.getScene().stopAnimation(this);
  80037. // Remove from scene
  80038. this.getScene().removeSkeleton(this);
  80039. };
  80040. /**
  80041. * Serialize the skeleton in a JSON object
  80042. * @returns a JSON object
  80043. */
  80044. Skeleton.prototype.serialize = function () {
  80045. var serializationObject = {};
  80046. serializationObject.name = this.name;
  80047. serializationObject.id = this.id;
  80048. if (this.dimensionsAtRest) {
  80049. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80050. }
  80051. serializationObject.bones = [];
  80052. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80053. for (var index = 0; index < this.bones.length; index++) {
  80054. var bone = this.bones[index];
  80055. var parent_2 = bone.getParent();
  80056. var serializedBone = {
  80057. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80058. name: bone.name,
  80059. matrix: bone.getBaseMatrix().toArray(),
  80060. rest: bone.getRestPose().toArray()
  80061. };
  80062. serializationObject.bones.push(serializedBone);
  80063. if (bone.length) {
  80064. serializedBone.length = bone.length;
  80065. }
  80066. if (bone.metadata) {
  80067. serializedBone.metadata = bone.metadata;
  80068. }
  80069. if (bone.animations && bone.animations.length > 0) {
  80070. serializedBone.animation = bone.animations[0].serialize();
  80071. }
  80072. serializationObject.ranges = [];
  80073. for (var name in this._ranges) {
  80074. var source = this._ranges[name];
  80075. if (!source) {
  80076. continue;
  80077. }
  80078. var range = {};
  80079. range.name = name;
  80080. range.from = source.from;
  80081. range.to = source.to;
  80082. serializationObject.ranges.push(range);
  80083. }
  80084. }
  80085. return serializationObject;
  80086. };
  80087. /**
  80088. * Creates a new skeleton from serialized data
  80089. * @param parsedSkeleton defines the serialized data
  80090. * @param scene defines the hosting scene
  80091. * @returns a new skeleton
  80092. */
  80093. Skeleton.Parse = function (parsedSkeleton, scene) {
  80094. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80095. if (parsedSkeleton.dimensionsAtRest) {
  80096. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80097. }
  80098. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80099. var index;
  80100. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80101. var parsedBone = parsedSkeleton.bones[index];
  80102. var parentBone = null;
  80103. if (parsedBone.parentBoneIndex > -1) {
  80104. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80105. }
  80106. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80107. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80108. if (parsedBone.length) {
  80109. bone.length = parsedBone.length;
  80110. }
  80111. if (parsedBone.metadata) {
  80112. bone.metadata = parsedBone.metadata;
  80113. }
  80114. if (parsedBone.animation) {
  80115. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80116. }
  80117. }
  80118. // placed after bones, so createAnimationRange can cascade down
  80119. if (parsedSkeleton.ranges) {
  80120. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80121. var data = parsedSkeleton.ranges[index];
  80122. skeleton.createAnimationRange(data.name, data.from, data.to);
  80123. }
  80124. }
  80125. return skeleton;
  80126. };
  80127. /**
  80128. * Compute all node absolute transforms
  80129. * @param forceUpdate defines if computation must be done even if cache is up to date
  80130. */
  80131. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80132. if (forceUpdate === void 0) { forceUpdate = false; }
  80133. var renderId = this._scene.getRenderId();
  80134. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80135. this.bones[0].computeAbsoluteTransforms();
  80136. this._lastAbsoluteTransformsUpdateId = renderId;
  80137. }
  80138. };
  80139. /**
  80140. * Gets the root pose matrix
  80141. * @returns a matrix
  80142. */
  80143. Skeleton.prototype.getPoseMatrix = function () {
  80144. var poseMatrix = null;
  80145. if (this._meshesWithPoseMatrix.length > 0) {
  80146. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80147. }
  80148. return poseMatrix;
  80149. };
  80150. /**
  80151. * Sorts bones per internal index
  80152. */
  80153. Skeleton.prototype.sortBones = function () {
  80154. var bones = new Array();
  80155. var visited = new Array(this.bones.length);
  80156. for (var index = 0; index < this.bones.length; index++) {
  80157. this._sortBones(index, bones, visited);
  80158. }
  80159. this.bones = bones;
  80160. };
  80161. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80162. if (visited[index]) {
  80163. return;
  80164. }
  80165. visited[index] = true;
  80166. var bone = this.bones[index];
  80167. if (bone._index === undefined) {
  80168. bone._index = index;
  80169. }
  80170. var parentBone = bone.getParent();
  80171. if (parentBone) {
  80172. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80173. }
  80174. bones.push(bone);
  80175. };
  80176. return Skeleton;
  80177. }());
  80178. BABYLON.Skeleton = Skeleton;
  80179. })(BABYLON || (BABYLON = {}));
  80180. //# sourceMappingURL=babylon.skeleton.js.map
  80181. var BABYLON;
  80182. (function (BABYLON) {
  80183. var SphericalPolynomial = /** @class */ (function () {
  80184. function SphericalPolynomial() {
  80185. this.x = BABYLON.Vector3.Zero();
  80186. this.y = BABYLON.Vector3.Zero();
  80187. this.z = BABYLON.Vector3.Zero();
  80188. this.xx = BABYLON.Vector3.Zero();
  80189. this.yy = BABYLON.Vector3.Zero();
  80190. this.zz = BABYLON.Vector3.Zero();
  80191. this.xy = BABYLON.Vector3.Zero();
  80192. this.yz = BABYLON.Vector3.Zero();
  80193. this.zx = BABYLON.Vector3.Zero();
  80194. }
  80195. SphericalPolynomial.prototype.addAmbient = function (color) {
  80196. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80197. this.xx = this.xx.add(colorVector);
  80198. this.yy = this.yy.add(colorVector);
  80199. this.zz = this.zz.add(colorVector);
  80200. };
  80201. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80202. var result = new SphericalPolynomial();
  80203. result.x = harmonics.L11.scale(1.02333);
  80204. result.y = harmonics.L1_1.scale(1.02333);
  80205. result.z = harmonics.L10.scale(1.02333);
  80206. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80207. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80208. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80209. result.yz = harmonics.L2_1.scale(0.858086);
  80210. result.zx = harmonics.L21.scale(0.858086);
  80211. result.xy = harmonics.L2_2.scale(0.858086);
  80212. result.scale(1.0 / Math.PI);
  80213. return result;
  80214. };
  80215. SphericalPolynomial.prototype.scale = function (scale) {
  80216. this.x = this.x.scale(scale);
  80217. this.y = this.y.scale(scale);
  80218. this.z = this.z.scale(scale);
  80219. this.xx = this.xx.scale(scale);
  80220. this.yy = this.yy.scale(scale);
  80221. this.zz = this.zz.scale(scale);
  80222. this.yz = this.yz.scale(scale);
  80223. this.zx = this.zx.scale(scale);
  80224. this.xy = this.xy.scale(scale);
  80225. };
  80226. return SphericalPolynomial;
  80227. }());
  80228. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80229. var SphericalHarmonics = /** @class */ (function () {
  80230. function SphericalHarmonics() {
  80231. this.L00 = BABYLON.Vector3.Zero();
  80232. this.L1_1 = BABYLON.Vector3.Zero();
  80233. this.L10 = BABYLON.Vector3.Zero();
  80234. this.L11 = BABYLON.Vector3.Zero();
  80235. this.L2_2 = BABYLON.Vector3.Zero();
  80236. this.L2_1 = BABYLON.Vector3.Zero();
  80237. this.L20 = BABYLON.Vector3.Zero();
  80238. this.L21 = BABYLON.Vector3.Zero();
  80239. this.L22 = BABYLON.Vector3.Zero();
  80240. }
  80241. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80242. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80243. var c = colorVector.scale(deltaSolidAngle);
  80244. this.L00 = this.L00.add(c.scale(0.282095));
  80245. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80246. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80247. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80248. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80249. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80250. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80251. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80252. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80253. };
  80254. SphericalHarmonics.prototype.scale = function (scale) {
  80255. this.L00 = this.L00.scale(scale);
  80256. this.L1_1 = this.L1_1.scale(scale);
  80257. this.L10 = this.L10.scale(scale);
  80258. this.L11 = this.L11.scale(scale);
  80259. this.L2_2 = this.L2_2.scale(scale);
  80260. this.L2_1 = this.L2_1.scale(scale);
  80261. this.L20 = this.L20.scale(scale);
  80262. this.L21 = this.L21.scale(scale);
  80263. this.L22 = this.L22.scale(scale);
  80264. };
  80265. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80266. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80267. //
  80268. // E_lm = A_l * L_lm
  80269. //
  80270. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80271. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80272. // the scaling factors are given in equation 9.
  80273. // Constant (Band 0)
  80274. this.L00 = this.L00.scale(3.141593);
  80275. // Linear (Band 1)
  80276. this.L1_1 = this.L1_1.scale(2.094395);
  80277. this.L10 = this.L10.scale(2.094395);
  80278. this.L11 = this.L11.scale(2.094395);
  80279. // Quadratic (Band 2)
  80280. this.L2_2 = this.L2_2.scale(0.785398);
  80281. this.L2_1 = this.L2_1.scale(0.785398);
  80282. this.L20 = this.L20.scale(0.785398);
  80283. this.L21 = this.L21.scale(0.785398);
  80284. this.L22 = this.L22.scale(0.785398);
  80285. };
  80286. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80287. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80288. // L = (1/pi) * E * rho
  80289. //
  80290. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80291. this.scale(1.0 / Math.PI);
  80292. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80293. // (The pixel shader must apply albedo after texture fetches, etc).
  80294. };
  80295. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80296. var result = new SphericalHarmonics();
  80297. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80298. result.L1_1 = polynomial.y.scale(0.977204);
  80299. result.L10 = polynomial.z.scale(0.977204);
  80300. result.L11 = polynomial.x.scale(0.977204);
  80301. result.L2_2 = polynomial.xy.scale(1.16538);
  80302. result.L2_1 = polynomial.yz.scale(1.16538);
  80303. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80304. result.L21 = polynomial.zx.scale(1.16538);
  80305. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80306. result.scale(Math.PI);
  80307. return result;
  80308. };
  80309. return SphericalHarmonics;
  80310. }());
  80311. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80312. })(BABYLON || (BABYLON = {}));
  80313. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80314. var BABYLON;
  80315. (function (BABYLON) {
  80316. var FileFaceOrientation = /** @class */ (function () {
  80317. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80318. this.name = name;
  80319. this.worldAxisForNormal = worldAxisForNormal;
  80320. this.worldAxisForFileX = worldAxisForFileX;
  80321. this.worldAxisForFileY = worldAxisForFileY;
  80322. }
  80323. return FileFaceOrientation;
  80324. }());
  80325. ;
  80326. /**
  80327. * Helper class dealing with the extraction of spherical polynomial dataArray
  80328. * from a cube map.
  80329. */
  80330. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80331. function CubeMapToSphericalPolynomialTools() {
  80332. }
  80333. /**
  80334. * Converts a texture to the according Spherical Polynomial data.
  80335. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80336. *
  80337. * @param texture The texture to extract the information from.
  80338. * @return The Spherical Polynomial data.
  80339. */
  80340. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80341. if (!texture.isCube) {
  80342. // Only supports cube Textures currently.
  80343. return null;
  80344. }
  80345. var size = texture.getSize().width;
  80346. var right = texture.readPixels(0);
  80347. var left = texture.readPixels(1);
  80348. var up;
  80349. var down;
  80350. if (texture.isRenderTarget) {
  80351. up = texture.readPixels(3);
  80352. down = texture.readPixels(2);
  80353. }
  80354. else {
  80355. up = texture.readPixels(2);
  80356. down = texture.readPixels(3);
  80357. }
  80358. var front = texture.readPixels(4);
  80359. var back = texture.readPixels(5);
  80360. var gammaSpace = texture.gammaSpace;
  80361. // Always read as RGBA.
  80362. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80363. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80364. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80365. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80366. }
  80367. var cubeInfo = {
  80368. size: size,
  80369. right: right,
  80370. left: left,
  80371. up: up,
  80372. down: down,
  80373. front: front,
  80374. back: back,
  80375. format: format,
  80376. type: type,
  80377. gammaSpace: gammaSpace,
  80378. };
  80379. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80380. };
  80381. /**
  80382. * Converts a cubemap to the according Spherical Polynomial data.
  80383. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80384. *
  80385. * @param cubeInfo The Cube map to extract the information from.
  80386. * @return The Spherical Polynomial data.
  80387. */
  80388. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80389. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80390. var totalSolidAngle = 0.0;
  80391. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80392. var du = 2.0 / cubeInfo.size;
  80393. var dv = du;
  80394. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80395. var minUV = du * 0.5 - 1.0;
  80396. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80397. var fileFace = this.FileFaces[faceIndex];
  80398. var dataArray = cubeInfo[fileFace.name];
  80399. var v = minUV;
  80400. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80401. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80402. // Because SP is still linear, so summation is fine in that basis.
  80403. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80404. for (var y = 0; y < cubeInfo.size; y++) {
  80405. var u = minUV;
  80406. for (var x = 0; x < cubeInfo.size; x++) {
  80407. // World direction (not normalised)
  80408. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80409. worldDirection.normalize();
  80410. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80411. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80412. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80413. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80414. // Handle Integer types.
  80415. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80416. r /= 255;
  80417. g /= 255;
  80418. b /= 255;
  80419. }
  80420. // Handle Gamma space textures.
  80421. if (cubeInfo.gammaSpace) {
  80422. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80423. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80424. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80425. }
  80426. var color = new BABYLON.Color3(r, g, b);
  80427. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80428. totalSolidAngle += deltaSolidAngle;
  80429. u += du;
  80430. }
  80431. v += dv;
  80432. }
  80433. }
  80434. // Solid angle for entire sphere is 4*pi
  80435. var sphereSolidAngle = 4.0 * Math.PI;
  80436. // Adjust the solid angle to allow for how many faces we processed.
  80437. var facesProcessed = 6.0;
  80438. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80439. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80440. // This is needed because the numerical integration over the cube uses a
  80441. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80442. // and also to compensate for accumulative error due to float precision in the summation.
  80443. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80444. sphericalHarmonics.scale(correctionFactor);
  80445. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80446. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80447. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80448. };
  80449. CubeMapToSphericalPolynomialTools.FileFaces = [
  80450. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80451. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80452. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80453. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80454. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80455. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80456. ];
  80457. return CubeMapToSphericalPolynomialTools;
  80458. }());
  80459. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80460. })(BABYLON || (BABYLON = {}));
  80461. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80462. var BABYLON;
  80463. (function (BABYLON) {
  80464. /**
  80465. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80466. */
  80467. var PanoramaToCubeMapTools = /** @class */ (function () {
  80468. function PanoramaToCubeMapTools() {
  80469. }
  80470. /**
  80471. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80472. *
  80473. * @param float32Array The source data.
  80474. * @param inputWidth The width of the input panorama.
  80475. * @param inputhHeight The height of the input panorama.
  80476. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80477. * @return The cubemap data
  80478. */
  80479. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80480. if (!float32Array) {
  80481. throw "ConvertPanoramaToCubemap: input cannot be null";
  80482. }
  80483. if (float32Array.length != inputWidth * inputHeight * 3) {
  80484. throw "ConvertPanoramaToCubemap: input size is wrong";
  80485. }
  80486. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80487. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80488. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80489. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80490. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80491. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80492. return {
  80493. front: textureFront,
  80494. back: textureBack,
  80495. left: textureLeft,
  80496. right: textureRight,
  80497. up: textureUp,
  80498. down: textureDown,
  80499. size: size,
  80500. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80501. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80502. gammaSpace: false,
  80503. };
  80504. };
  80505. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80506. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80507. var textureArray = new Float32Array(buffer);
  80508. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80509. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80510. var dy = 1 / texSize;
  80511. var fy = 0;
  80512. for (var y = 0; y < texSize; y++) {
  80513. var xv1 = faceData[0];
  80514. var xv2 = faceData[2];
  80515. for (var x = 0; x < texSize; x++) {
  80516. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80517. v.normalize();
  80518. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80519. // 3 channels per pixels
  80520. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80521. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80522. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80523. xv1 = xv1.add(rotDX1);
  80524. xv2 = xv2.add(rotDX2);
  80525. }
  80526. fy += dy;
  80527. }
  80528. return textureArray;
  80529. };
  80530. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80531. var theta = Math.atan2(vDir.z, vDir.x);
  80532. var phi = Math.acos(vDir.y);
  80533. while (theta < -Math.PI)
  80534. theta += 2 * Math.PI;
  80535. while (theta > Math.PI)
  80536. theta -= 2 * Math.PI;
  80537. var dx = theta / Math.PI;
  80538. var dy = phi / Math.PI;
  80539. // recenter.
  80540. dx = dx * 0.5 + 0.5;
  80541. var px = Math.round(dx * inputWidth);
  80542. if (px < 0)
  80543. px = 0;
  80544. else if (px >= inputWidth)
  80545. px = inputWidth - 1;
  80546. var py = Math.round(dy * inputHeight);
  80547. if (py < 0)
  80548. py = 0;
  80549. else if (py >= inputHeight)
  80550. py = inputHeight - 1;
  80551. var inputY = (inputHeight - py - 1);
  80552. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80553. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80554. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80555. return {
  80556. r: r,
  80557. g: g,
  80558. b: b
  80559. };
  80560. };
  80561. PanoramaToCubeMapTools.FACE_FRONT = [
  80562. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80563. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80564. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80565. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80566. ];
  80567. PanoramaToCubeMapTools.FACE_BACK = [
  80568. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80569. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80570. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80571. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80572. ];
  80573. PanoramaToCubeMapTools.FACE_RIGHT = [
  80574. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80575. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80576. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80577. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80578. ];
  80579. PanoramaToCubeMapTools.FACE_LEFT = [
  80580. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80581. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80582. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80583. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80584. ];
  80585. PanoramaToCubeMapTools.FACE_DOWN = [
  80586. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80587. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80588. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80589. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80590. ];
  80591. PanoramaToCubeMapTools.FACE_UP = [
  80592. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80593. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80594. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80595. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80596. ];
  80597. return PanoramaToCubeMapTools;
  80598. }());
  80599. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80600. })(BABYLON || (BABYLON = {}));
  80601. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80602. var BABYLON;
  80603. (function (BABYLON) {
  80604. ;
  80605. /**
  80606. * This groups tools to convert HDR texture to native colors array.
  80607. */
  80608. var HDRTools = /** @class */ (function () {
  80609. function HDRTools() {
  80610. }
  80611. HDRTools.Ldexp = function (mantissa, exponent) {
  80612. if (exponent > 1023) {
  80613. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80614. }
  80615. if (exponent < -1074) {
  80616. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80617. }
  80618. return mantissa * Math.pow(2, exponent);
  80619. };
  80620. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80621. if (exponent > 0) { /*nonzero pixel*/
  80622. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80623. float32array[index + 0] = red * exponent;
  80624. float32array[index + 1] = green * exponent;
  80625. float32array[index + 2] = blue * exponent;
  80626. }
  80627. else {
  80628. float32array[index + 0] = 0;
  80629. float32array[index + 1] = 0;
  80630. float32array[index + 2] = 0;
  80631. }
  80632. };
  80633. HDRTools.readStringLine = function (uint8array, startIndex) {
  80634. var line = "";
  80635. var character = "";
  80636. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80637. character = String.fromCharCode(uint8array[i]);
  80638. if (character == "\n") {
  80639. break;
  80640. }
  80641. line += character;
  80642. }
  80643. return line;
  80644. };
  80645. /**
  80646. * Reads header information from an RGBE texture stored in a native array.
  80647. * More information on this format are available here:
  80648. * https://en.wikipedia.org/wiki/RGBE_image_format
  80649. *
  80650. * @param uint8array The binary file stored in native array.
  80651. * @return The header information.
  80652. */
  80653. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80654. var height = 0;
  80655. var width = 0;
  80656. var line = this.readStringLine(uint8array, 0);
  80657. if (line[0] != '#' || line[1] != '?') {
  80658. throw "Bad HDR Format.";
  80659. }
  80660. var endOfHeader = false;
  80661. var findFormat = false;
  80662. var lineIndex = 0;
  80663. do {
  80664. lineIndex += (line.length + 1);
  80665. line = this.readStringLine(uint8array, lineIndex);
  80666. if (line == "FORMAT=32-bit_rle_rgbe") {
  80667. findFormat = true;
  80668. }
  80669. else if (line.length == 0) {
  80670. endOfHeader = true;
  80671. }
  80672. } while (!endOfHeader);
  80673. if (!findFormat) {
  80674. throw "HDR Bad header format, unsupported FORMAT";
  80675. }
  80676. lineIndex += (line.length + 1);
  80677. line = this.readStringLine(uint8array, lineIndex);
  80678. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80679. var match = sizeRegexp.exec(line);
  80680. // TODO. Support +Y and -X if needed.
  80681. if (!match || match.length < 3) {
  80682. throw "HDR Bad header format, no size";
  80683. }
  80684. width = parseInt(match[2]);
  80685. height = parseInt(match[1]);
  80686. if (width < 8 || width > 0x7fff) {
  80687. throw "HDR Bad header format, unsupported size";
  80688. }
  80689. lineIndex += (line.length + 1);
  80690. return {
  80691. height: height,
  80692. width: width,
  80693. dataPosition: lineIndex
  80694. };
  80695. };
  80696. /**
  80697. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80698. * This RGBE texture needs to store the information as a panorama.
  80699. *
  80700. * More information on this format are available here:
  80701. * https://en.wikipedia.org/wiki/RGBE_image_format
  80702. *
  80703. * @param buffer The binary file stored in an array buffer.
  80704. * @param size The expected size of the extracted cubemap.
  80705. * @return The Cube Map information.
  80706. */
  80707. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80708. var uint8array = new Uint8Array(buffer);
  80709. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80710. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80711. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80712. return cubeMapData;
  80713. };
  80714. /**
  80715. * Returns the pixels data extracted from an RGBE texture.
  80716. * This pixels will be stored left to right up to down in the R G B order in one array.
  80717. *
  80718. * More information on this format are available here:
  80719. * https://en.wikipedia.org/wiki/RGBE_image_format
  80720. *
  80721. * @param uint8array The binary file stored in an array buffer.
  80722. * @param hdrInfo The header information of the file.
  80723. * @return The pixels data in RGB right to left up to down order.
  80724. */
  80725. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80726. // Keep for multi format supports.
  80727. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80728. };
  80729. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80730. var num_scanlines = hdrInfo.height;
  80731. var scanline_width = hdrInfo.width;
  80732. var a, b, c, d, count;
  80733. var dataIndex = hdrInfo.dataPosition;
  80734. var index = 0, endIndex = 0, i = 0;
  80735. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80736. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80737. // 3 channels of 4 bytes per pixel in float.
  80738. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80739. var resultArray = new Float32Array(resultBuffer);
  80740. // read in each successive scanline
  80741. while (num_scanlines > 0) {
  80742. a = uint8array[dataIndex++];
  80743. b = uint8array[dataIndex++];
  80744. c = uint8array[dataIndex++];
  80745. d = uint8array[dataIndex++];
  80746. if (a != 2 || b != 2 || (c & 0x80)) {
  80747. // this file is not run length encoded
  80748. throw "HDR Bad header format, not RLE";
  80749. }
  80750. if (((c << 8) | d) != scanline_width) {
  80751. throw "HDR Bad header format, wrong scan line width";
  80752. }
  80753. index = 0;
  80754. // read each of the four channels for the scanline into the buffer
  80755. for (i = 0; i < 4; i++) {
  80756. endIndex = (i + 1) * scanline_width;
  80757. while (index < endIndex) {
  80758. a = uint8array[dataIndex++];
  80759. b = uint8array[dataIndex++];
  80760. if (a > 128) {
  80761. // a run of the same value
  80762. count = a - 128;
  80763. if ((count == 0) || (count > endIndex - index)) {
  80764. throw "HDR Bad Format, bad scanline data (run)";
  80765. }
  80766. while (count-- > 0) {
  80767. scanLineArray[index++] = b;
  80768. }
  80769. }
  80770. else {
  80771. // a non-run
  80772. count = a;
  80773. if ((count == 0) || (count > endIndex - index)) {
  80774. throw "HDR Bad Format, bad scanline data (non-run)";
  80775. }
  80776. scanLineArray[index++] = b;
  80777. if (--count > 0) {
  80778. for (var j = 0; j < count; j++) {
  80779. scanLineArray[index++] = uint8array[dataIndex++];
  80780. }
  80781. }
  80782. }
  80783. }
  80784. }
  80785. // now convert data from buffer into floats
  80786. for (i = 0; i < scanline_width; i++) {
  80787. a = scanLineArray[i];
  80788. b = scanLineArray[i + scanline_width];
  80789. c = scanLineArray[i + 2 * scanline_width];
  80790. d = scanLineArray[i + 3 * scanline_width];
  80791. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80792. }
  80793. num_scanlines--;
  80794. }
  80795. return resultArray;
  80796. };
  80797. return HDRTools;
  80798. }());
  80799. BABYLON.HDRTools = HDRTools;
  80800. })(BABYLON || (BABYLON = {}));
  80801. //# sourceMappingURL=babylon.hdr.js.map
  80802. var BABYLON;
  80803. (function (BABYLON) {
  80804. /**
  80805. * This represents a texture coming from an HDR input.
  80806. *
  80807. * The only supported format is currently panorama picture stored in RGBE format.
  80808. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80809. */
  80810. var HDRCubeTexture = /** @class */ (function (_super) {
  80811. __extends(HDRCubeTexture, _super);
  80812. /**
  80813. * Instantiates an HDRTexture from the following parameters.
  80814. *
  80815. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80816. * @param scene The scene the texture will be used in
  80817. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80818. * @param noMipmap Forces to not generate the mipmap if true
  80819. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80820. * @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)
  80821. * @param reserved Reserved flag for internal use.
  80822. */
  80823. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80824. if (noMipmap === void 0) { noMipmap = false; }
  80825. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80826. if (gammaSpace === void 0) { gammaSpace = false; }
  80827. if (reserved === void 0) { reserved = false; }
  80828. if (onLoad === void 0) { onLoad = null; }
  80829. if (onError === void 0) { onError = null; }
  80830. var _this = _super.call(this, scene) || this;
  80831. _this._generateHarmonics = true;
  80832. _this._onLoad = null;
  80833. _this._onError = null;
  80834. /**
  80835. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80836. */
  80837. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80838. _this._isBlocking = true;
  80839. _this._rotationY = 0;
  80840. /**
  80841. * Gets or sets the center of the bounding box associated with the cube texture
  80842. * It must define where the camera used to render the texture was set
  80843. */
  80844. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80845. if (!url) {
  80846. return _this;
  80847. }
  80848. _this.name = url;
  80849. _this.url = url;
  80850. _this.hasAlpha = false;
  80851. _this.isCube = true;
  80852. _this._textureMatrix = BABYLON.Matrix.Identity();
  80853. _this._onLoad = onLoad;
  80854. _this._onError = onError;
  80855. _this.gammaSpace = gammaSpace;
  80856. _this._noMipmap = noMipmap;
  80857. _this._size = size;
  80858. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80859. if (!_this._texture) {
  80860. if (!scene.useDelayedTextureLoading) {
  80861. _this.loadTexture();
  80862. }
  80863. else {
  80864. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80865. }
  80866. }
  80867. return _this;
  80868. }
  80869. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80870. /**
  80871. * Gets wether or not the texture is blocking during loading.
  80872. */
  80873. get: function () {
  80874. return this._isBlocking;
  80875. },
  80876. /**
  80877. * Sets wether or not the texture is blocking during loading.
  80878. */
  80879. set: function (value) {
  80880. this._isBlocking = value;
  80881. },
  80882. enumerable: true,
  80883. configurable: true
  80884. });
  80885. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80886. /**
  80887. * Gets texture matrix rotation angle around Y axis radians.
  80888. */
  80889. get: function () {
  80890. return this._rotationY;
  80891. },
  80892. /**
  80893. * Sets texture matrix rotation angle around Y axis in radians.
  80894. */
  80895. set: function (value) {
  80896. this._rotationY = value;
  80897. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80898. },
  80899. enumerable: true,
  80900. configurable: true
  80901. });
  80902. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80903. get: function () {
  80904. return this._boundingBoxSize;
  80905. },
  80906. /**
  80907. * Gets or sets the size of the bounding box associated with the cube texture
  80908. * When defined, the cubemap will switch to local mode
  80909. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80910. * @example https://www.babylonjs-playground.com/#RNASML
  80911. */
  80912. set: function (value) {
  80913. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80914. return;
  80915. }
  80916. this._boundingBoxSize = value;
  80917. var scene = this.getScene();
  80918. if (scene) {
  80919. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80920. }
  80921. },
  80922. enumerable: true,
  80923. configurable: true
  80924. });
  80925. /**
  80926. * Occurs when the file is raw .hdr file.
  80927. */
  80928. HDRCubeTexture.prototype.loadTexture = function () {
  80929. var _this = this;
  80930. var callback = function (buffer) {
  80931. var scene = _this.getScene();
  80932. if (!scene) {
  80933. return null;
  80934. }
  80935. // Extract the raw linear data.
  80936. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80937. // Generate harmonics if needed.
  80938. if (_this._generateHarmonics) {
  80939. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80940. _this.sphericalPolynomial = sphericalPolynomial;
  80941. }
  80942. var results = [];
  80943. var byteArray = null;
  80944. // Push each faces.
  80945. for (var j = 0; j < 6; j++) {
  80946. // Create uintarray fallback.
  80947. if (!scene.getEngine().getCaps().textureFloat) {
  80948. // 3 channels of 1 bytes per pixel in bytes.
  80949. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80950. byteArray = new Uint8Array(byteBuffer);
  80951. }
  80952. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80953. // If special cases.
  80954. if (_this.gammaSpace || byteArray) {
  80955. for (var i = 0; i < _this._size * _this._size; i++) {
  80956. // Put in gamma space if requested.
  80957. if (_this.gammaSpace) {
  80958. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80959. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80960. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80961. }
  80962. // Convert to int texture for fallback.
  80963. if (byteArray) {
  80964. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80965. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80966. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80967. // May use luminance instead if the result is not accurate.
  80968. var max = Math.max(Math.max(r, g), b);
  80969. if (max > 255) {
  80970. var scale = 255 / max;
  80971. r *= scale;
  80972. g *= scale;
  80973. b *= scale;
  80974. }
  80975. byteArray[(i * 3) + 0] = r;
  80976. byteArray[(i * 3) + 1] = g;
  80977. byteArray[(i * 3) + 2] = b;
  80978. }
  80979. }
  80980. }
  80981. if (byteArray) {
  80982. results.push(byteArray);
  80983. }
  80984. else {
  80985. results.push(dataFace);
  80986. }
  80987. }
  80988. return results;
  80989. };
  80990. var scene = this.getScene();
  80991. if (scene) {
  80992. 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);
  80993. }
  80994. };
  80995. HDRCubeTexture.prototype.clone = function () {
  80996. var scene = this.getScene();
  80997. if (!scene) {
  80998. return this;
  80999. }
  81000. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81001. // Base texture
  81002. newTexture.level = this.level;
  81003. newTexture.wrapU = this.wrapU;
  81004. newTexture.wrapV = this.wrapV;
  81005. newTexture.coordinatesIndex = this.coordinatesIndex;
  81006. newTexture.coordinatesMode = this.coordinatesMode;
  81007. return newTexture;
  81008. };
  81009. // Methods
  81010. HDRCubeTexture.prototype.delayLoad = function () {
  81011. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81012. return;
  81013. }
  81014. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81015. this._texture = this._getFromCache(this.url, this._noMipmap);
  81016. if (!this._texture) {
  81017. this.loadTexture();
  81018. }
  81019. };
  81020. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81021. return this._textureMatrix;
  81022. };
  81023. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81024. this._textureMatrix = value;
  81025. };
  81026. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81027. var texture = null;
  81028. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81029. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81030. texture.name = parsedTexture.name;
  81031. texture.hasAlpha = parsedTexture.hasAlpha;
  81032. texture.level = parsedTexture.level;
  81033. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81034. texture.isBlocking = parsedTexture.isBlocking;
  81035. }
  81036. if (texture) {
  81037. if (parsedTexture.boundingBoxPosition) {
  81038. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81039. }
  81040. if (parsedTexture.boundingBoxSize) {
  81041. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81042. }
  81043. if (parsedTexture.rotationY) {
  81044. texture.rotationY = parsedTexture.rotationY;
  81045. }
  81046. }
  81047. return texture;
  81048. };
  81049. HDRCubeTexture.prototype.serialize = function () {
  81050. if (!this.name) {
  81051. return null;
  81052. }
  81053. var serializationObject = {};
  81054. serializationObject.name = this.name;
  81055. serializationObject.hasAlpha = this.hasAlpha;
  81056. serializationObject.isCube = true;
  81057. serializationObject.level = this.level;
  81058. serializationObject.size = this._size;
  81059. serializationObject.coordinatesMode = this.coordinatesMode;
  81060. serializationObject.useInGammaSpace = this.gammaSpace;
  81061. serializationObject.generateHarmonics = this._generateHarmonics;
  81062. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81063. serializationObject.noMipmap = this._noMipmap;
  81064. serializationObject.isBlocking = this._isBlocking;
  81065. serializationObject.rotationY = this._rotationY;
  81066. return serializationObject;
  81067. };
  81068. HDRCubeTexture._facesMapping = [
  81069. "right",
  81070. "left",
  81071. "up",
  81072. "down",
  81073. "front",
  81074. "back"
  81075. ];
  81076. return HDRCubeTexture;
  81077. }(BABYLON.BaseTexture));
  81078. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81079. })(BABYLON || (BABYLON = {}));
  81080. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81081. var BABYLON;
  81082. (function (BABYLON) {
  81083. var IndexedVector2 = /** @class */ (function (_super) {
  81084. __extends(IndexedVector2, _super);
  81085. function IndexedVector2(original, index) {
  81086. var _this = _super.call(this, original.x, original.y) || this;
  81087. _this.index = index;
  81088. return _this;
  81089. }
  81090. return IndexedVector2;
  81091. }(BABYLON.Vector2));
  81092. var PolygonPoints = /** @class */ (function () {
  81093. function PolygonPoints() {
  81094. this.elements = new Array();
  81095. }
  81096. PolygonPoints.prototype.add = function (originalPoints) {
  81097. var _this = this;
  81098. var result = new Array();
  81099. originalPoints.forEach(function (point) {
  81100. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81101. var newPoint = new IndexedVector2(point, _this.elements.length);
  81102. result.push(newPoint);
  81103. _this.elements.push(newPoint);
  81104. }
  81105. });
  81106. return result;
  81107. };
  81108. PolygonPoints.prototype.computeBounds = function () {
  81109. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81110. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81111. this.elements.forEach(function (point) {
  81112. // x
  81113. if (point.x < lmin.x) {
  81114. lmin.x = point.x;
  81115. }
  81116. else if (point.x > lmax.x) {
  81117. lmax.x = point.x;
  81118. }
  81119. // y
  81120. if (point.y < lmin.y) {
  81121. lmin.y = point.y;
  81122. }
  81123. else if (point.y > lmax.y) {
  81124. lmax.y = point.y;
  81125. }
  81126. });
  81127. return {
  81128. min: lmin,
  81129. max: lmax,
  81130. width: lmax.x - lmin.x,
  81131. height: lmax.y - lmin.y
  81132. };
  81133. };
  81134. return PolygonPoints;
  81135. }());
  81136. var Polygon = /** @class */ (function () {
  81137. function Polygon() {
  81138. }
  81139. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81140. return [
  81141. new BABYLON.Vector2(xmin, ymin),
  81142. new BABYLON.Vector2(xmax, ymin),
  81143. new BABYLON.Vector2(xmax, ymax),
  81144. new BABYLON.Vector2(xmin, ymax)
  81145. ];
  81146. };
  81147. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81148. if (cx === void 0) { cx = 0; }
  81149. if (cy === void 0) { cy = 0; }
  81150. if (numberOfSides === void 0) { numberOfSides = 32; }
  81151. var result = new Array();
  81152. var angle = 0;
  81153. var increment = (Math.PI * 2) / numberOfSides;
  81154. for (var i = 0; i < numberOfSides; i++) {
  81155. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81156. angle -= increment;
  81157. }
  81158. return result;
  81159. };
  81160. Polygon.Parse = function (input) {
  81161. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81162. var i, result = [];
  81163. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81164. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81165. }
  81166. return result;
  81167. };
  81168. Polygon.StartingAt = function (x, y) {
  81169. return BABYLON.Path2.StartingAt(x, y);
  81170. };
  81171. return Polygon;
  81172. }());
  81173. BABYLON.Polygon = Polygon;
  81174. var PolygonMeshBuilder = /** @class */ (function () {
  81175. function PolygonMeshBuilder(name, contours, scene) {
  81176. this._points = new PolygonPoints();
  81177. this._outlinepoints = new PolygonPoints();
  81178. this._holes = new Array();
  81179. this._epoints = new Array();
  81180. this._eholes = new Array();
  81181. this._name = name;
  81182. this._scene = scene;
  81183. var points;
  81184. if (contours instanceof BABYLON.Path2) {
  81185. points = contours.getPoints();
  81186. }
  81187. else {
  81188. points = contours;
  81189. }
  81190. this._addToepoint(points);
  81191. this._points.add(points);
  81192. this._outlinepoints.add(points);
  81193. if (typeof earcut === 'undefined') {
  81194. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81195. }
  81196. }
  81197. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81198. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81199. var p = points_1[_i];
  81200. this._epoints.push(p.x, p.y);
  81201. }
  81202. };
  81203. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81204. this._points.add(hole);
  81205. var holepoints = new PolygonPoints();
  81206. holepoints.add(hole);
  81207. this._holes.push(holepoints);
  81208. this._eholes.push(this._epoints.length / 2);
  81209. this._addToepoint(hole);
  81210. return this;
  81211. };
  81212. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81213. var _this = this;
  81214. if (updatable === void 0) { updatable = false; }
  81215. if (depth === void 0) { depth = 0; }
  81216. var result = new BABYLON.Mesh(this._name, this._scene);
  81217. var normals = new Array();
  81218. var positions = new Array();
  81219. var uvs = new Array();
  81220. var bounds = this._points.computeBounds();
  81221. this._points.elements.forEach(function (p) {
  81222. normals.push(0, 1.0, 0);
  81223. positions.push(p.x, 0, p.y);
  81224. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81225. });
  81226. var indices = new Array();
  81227. var res = earcut(this._epoints, this._eholes, 2);
  81228. for (var i = 0; i < res.length; i++) {
  81229. indices.push(res[i]);
  81230. }
  81231. if (depth > 0) {
  81232. var positionscount = (positions.length / 3); //get the current pointcount
  81233. this._points.elements.forEach(function (p) {
  81234. normals.push(0, -1.0, 0);
  81235. positions.push(p.x, -depth, p.y);
  81236. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81237. });
  81238. var totalCount = indices.length;
  81239. for (var i = 0; i < totalCount; i += 3) {
  81240. var i0 = indices[i + 0];
  81241. var i1 = indices[i + 1];
  81242. var i2 = indices[i + 2];
  81243. indices.push(i2 + positionscount);
  81244. indices.push(i1 + positionscount);
  81245. indices.push(i0 + positionscount);
  81246. }
  81247. //Add the sides
  81248. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81249. this._holes.forEach(function (hole) {
  81250. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81251. });
  81252. }
  81253. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81254. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81255. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81256. result.setIndices(indices);
  81257. return result;
  81258. };
  81259. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81260. var StartIndex = positions.length / 3;
  81261. var ulength = 0;
  81262. for (var i = 0; i < points.elements.length; i++) {
  81263. var p = points.elements[i];
  81264. var p1;
  81265. if ((i + 1) > points.elements.length - 1) {
  81266. p1 = points.elements[0];
  81267. }
  81268. else {
  81269. p1 = points.elements[i + 1];
  81270. }
  81271. positions.push(p.x, 0, p.y);
  81272. positions.push(p.x, -depth, p.y);
  81273. positions.push(p1.x, 0, p1.y);
  81274. positions.push(p1.x, -depth, p1.y);
  81275. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81276. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81277. var v3 = v2.subtract(v1);
  81278. var v4 = new BABYLON.Vector3(0, 1, 0);
  81279. var vn = BABYLON.Vector3.Cross(v3, v4);
  81280. vn = vn.normalize();
  81281. uvs.push(ulength / bounds.width, 0);
  81282. uvs.push(ulength / bounds.width, 1);
  81283. ulength += v3.length();
  81284. uvs.push((ulength / bounds.width), 0);
  81285. uvs.push((ulength / bounds.width), 1);
  81286. if (!flip) {
  81287. normals.push(-vn.x, -vn.y, -vn.z);
  81288. normals.push(-vn.x, -vn.y, -vn.z);
  81289. normals.push(-vn.x, -vn.y, -vn.z);
  81290. normals.push(-vn.x, -vn.y, -vn.z);
  81291. indices.push(StartIndex);
  81292. indices.push(StartIndex + 1);
  81293. indices.push(StartIndex + 2);
  81294. indices.push(StartIndex + 1);
  81295. indices.push(StartIndex + 3);
  81296. indices.push(StartIndex + 2);
  81297. }
  81298. else {
  81299. normals.push(vn.x, vn.y, vn.z);
  81300. normals.push(vn.x, vn.y, vn.z);
  81301. normals.push(vn.x, vn.y, vn.z);
  81302. normals.push(vn.x, vn.y, vn.z);
  81303. indices.push(StartIndex);
  81304. indices.push(StartIndex + 2);
  81305. indices.push(StartIndex + 1);
  81306. indices.push(StartIndex + 1);
  81307. indices.push(StartIndex + 2);
  81308. indices.push(StartIndex + 3);
  81309. }
  81310. StartIndex += 4;
  81311. }
  81312. ;
  81313. };
  81314. return PolygonMeshBuilder;
  81315. }());
  81316. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81317. })(BABYLON || (BABYLON = {}));
  81318. //# sourceMappingURL=babylon.polygonMesh.js.map
  81319. var BABYLON;
  81320. (function (BABYLON) {
  81321. // Unique ID when we import meshes from Babylon to CSG
  81322. var currentCSGMeshId = 0;
  81323. // # class Vertex
  81324. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81325. // one to provide additional features like texture coordinates and vertex
  81326. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81327. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81328. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81329. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81330. // is not used anywhere else.
  81331. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81332. var Vertex = /** @class */ (function () {
  81333. function Vertex(pos, normal, uv) {
  81334. this.pos = pos;
  81335. this.normal = normal;
  81336. this.uv = uv;
  81337. }
  81338. Vertex.prototype.clone = function () {
  81339. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81340. };
  81341. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81342. // orientation of a polygon is flipped.
  81343. Vertex.prototype.flip = function () {
  81344. this.normal = this.normal.scale(-1);
  81345. };
  81346. // Create a new vertex between this vertex and `other` by linearly
  81347. // interpolating all properties using a parameter of `t`. Subclasses should
  81348. // override this to interpolate additional properties.
  81349. Vertex.prototype.interpolate = function (other, t) {
  81350. 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));
  81351. };
  81352. return Vertex;
  81353. }());
  81354. // # class Plane
  81355. // Represents a plane in 3D space.
  81356. var Plane = /** @class */ (function () {
  81357. function Plane(normal, w) {
  81358. this.normal = normal;
  81359. this.w = w;
  81360. }
  81361. Plane.FromPoints = function (a, b, c) {
  81362. var v0 = c.subtract(a);
  81363. var v1 = b.subtract(a);
  81364. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81365. return null;
  81366. }
  81367. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81368. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81369. };
  81370. Plane.prototype.clone = function () {
  81371. return new Plane(this.normal.clone(), this.w);
  81372. };
  81373. Plane.prototype.flip = function () {
  81374. this.normal.scaleInPlace(-1);
  81375. this.w = -this.w;
  81376. };
  81377. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81378. // fragments in the appropriate lists. Coplanar polygons go into either
  81379. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81380. // respect to this plane. Polygons in front or in back of this plane go into
  81381. // either `front` or `back`.
  81382. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81383. var COPLANAR = 0;
  81384. var FRONT = 1;
  81385. var BACK = 2;
  81386. var SPANNING = 3;
  81387. // Classify each point as well as the entire polygon into one of the above
  81388. // four classes.
  81389. var polygonType = 0;
  81390. var types = [];
  81391. var i;
  81392. var t;
  81393. for (i = 0; i < polygon.vertices.length; i++) {
  81394. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81395. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81396. polygonType |= type;
  81397. types.push(type);
  81398. }
  81399. // Put the polygon in the correct list, splitting it when necessary.
  81400. switch (polygonType) {
  81401. case COPLANAR:
  81402. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81403. break;
  81404. case FRONT:
  81405. front.push(polygon);
  81406. break;
  81407. case BACK:
  81408. back.push(polygon);
  81409. break;
  81410. case SPANNING:
  81411. var f = [], b = [];
  81412. for (i = 0; i < polygon.vertices.length; i++) {
  81413. var j = (i + 1) % polygon.vertices.length;
  81414. var ti = types[i], tj = types[j];
  81415. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81416. if (ti !== BACK)
  81417. f.push(vi);
  81418. if (ti !== FRONT)
  81419. b.push(ti !== BACK ? vi.clone() : vi);
  81420. if ((ti | tj) === SPANNING) {
  81421. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81422. var v = vi.interpolate(vj, t);
  81423. f.push(v);
  81424. b.push(v.clone());
  81425. }
  81426. }
  81427. var poly;
  81428. if (f.length >= 3) {
  81429. poly = new Polygon(f, polygon.shared);
  81430. if (poly.plane)
  81431. front.push(poly);
  81432. }
  81433. if (b.length >= 3) {
  81434. poly = new Polygon(b, polygon.shared);
  81435. if (poly.plane)
  81436. back.push(poly);
  81437. }
  81438. break;
  81439. }
  81440. };
  81441. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81442. // point is on the plane.
  81443. Plane.EPSILON = 1e-5;
  81444. return Plane;
  81445. }());
  81446. // # class Polygon
  81447. // Represents a convex polygon. The vertices used to initialize a polygon must
  81448. // be coplanar and form a convex loop.
  81449. //
  81450. // Each convex polygon has a `shared` property, which is shared between all
  81451. // polygons that are clones of each other or were split from the same polygon.
  81452. // This can be used to define per-polygon properties (such as surface color).
  81453. var Polygon = /** @class */ (function () {
  81454. function Polygon(vertices, shared) {
  81455. this.vertices = vertices;
  81456. this.shared = shared;
  81457. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81458. }
  81459. Polygon.prototype.clone = function () {
  81460. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81461. return new Polygon(vertices, this.shared);
  81462. };
  81463. Polygon.prototype.flip = function () {
  81464. this.vertices.reverse().map(function (v) { v.flip(); });
  81465. this.plane.flip();
  81466. };
  81467. return Polygon;
  81468. }());
  81469. // # class Node
  81470. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81471. // by picking a polygon to split along. That polygon (and all other coplanar
  81472. // polygons) are added directly to that node and the other polygons are added to
  81473. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81474. // no distinction between internal and leaf nodes.
  81475. var Node = /** @class */ (function () {
  81476. function Node(polygons) {
  81477. this.plane = null;
  81478. this.front = null;
  81479. this.back = null;
  81480. this.polygons = new Array();
  81481. if (polygons) {
  81482. this.build(polygons);
  81483. }
  81484. }
  81485. Node.prototype.clone = function () {
  81486. var node = new Node();
  81487. node.plane = this.plane && this.plane.clone();
  81488. node.front = this.front && this.front.clone();
  81489. node.back = this.back && this.back.clone();
  81490. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81491. return node;
  81492. };
  81493. // Convert solid space to empty space and empty space to solid space.
  81494. Node.prototype.invert = function () {
  81495. for (var i = 0; i < this.polygons.length; i++) {
  81496. this.polygons[i].flip();
  81497. }
  81498. if (this.plane) {
  81499. this.plane.flip();
  81500. }
  81501. if (this.front) {
  81502. this.front.invert();
  81503. }
  81504. if (this.back) {
  81505. this.back.invert();
  81506. }
  81507. var temp = this.front;
  81508. this.front = this.back;
  81509. this.back = temp;
  81510. };
  81511. // Recursively remove all polygons in `polygons` that are inside this BSP
  81512. // tree.
  81513. Node.prototype.clipPolygons = function (polygons) {
  81514. if (!this.plane)
  81515. return polygons.slice();
  81516. var front = new Array(), back = new Array();
  81517. for (var i = 0; i < polygons.length; i++) {
  81518. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81519. }
  81520. if (this.front) {
  81521. front = this.front.clipPolygons(front);
  81522. }
  81523. if (this.back) {
  81524. back = this.back.clipPolygons(back);
  81525. }
  81526. else {
  81527. back = [];
  81528. }
  81529. return front.concat(back);
  81530. };
  81531. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81532. // `bsp`.
  81533. Node.prototype.clipTo = function (bsp) {
  81534. this.polygons = bsp.clipPolygons(this.polygons);
  81535. if (this.front)
  81536. this.front.clipTo(bsp);
  81537. if (this.back)
  81538. this.back.clipTo(bsp);
  81539. };
  81540. // Return a list of all polygons in this BSP tree.
  81541. Node.prototype.allPolygons = function () {
  81542. var polygons = this.polygons.slice();
  81543. if (this.front)
  81544. polygons = polygons.concat(this.front.allPolygons());
  81545. if (this.back)
  81546. polygons = polygons.concat(this.back.allPolygons());
  81547. return polygons;
  81548. };
  81549. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81550. // new polygons are filtered down to the bottom of the tree and become new
  81551. // nodes there. Each set of polygons is partitioned using the first polygon
  81552. // (no heuristic is used to pick a good split).
  81553. Node.prototype.build = function (polygons) {
  81554. if (!polygons.length)
  81555. return;
  81556. if (!this.plane)
  81557. this.plane = polygons[0].plane.clone();
  81558. var front = new Array(), back = new Array();
  81559. for (var i = 0; i < polygons.length; i++) {
  81560. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81561. }
  81562. if (front.length) {
  81563. if (!this.front)
  81564. this.front = new Node();
  81565. this.front.build(front);
  81566. }
  81567. if (back.length) {
  81568. if (!this.back)
  81569. this.back = new Node();
  81570. this.back.build(back);
  81571. }
  81572. };
  81573. return Node;
  81574. }());
  81575. var CSG = /** @class */ (function () {
  81576. function CSG() {
  81577. this.polygons = new Array();
  81578. }
  81579. // Convert BABYLON.Mesh to BABYLON.CSG
  81580. CSG.FromMesh = function (mesh) {
  81581. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81582. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81583. if (mesh instanceof BABYLON.Mesh) {
  81584. mesh.computeWorldMatrix(true);
  81585. matrix = mesh.getWorldMatrix();
  81586. meshPosition = mesh.position.clone();
  81587. meshRotation = mesh.rotation.clone();
  81588. if (mesh.rotationQuaternion) {
  81589. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81590. }
  81591. meshScaling = mesh.scaling.clone();
  81592. }
  81593. else {
  81594. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81595. }
  81596. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81597. var subMeshes = mesh.subMeshes;
  81598. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81599. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81600. vertices = [];
  81601. for (var j = 0; j < 3; j++) {
  81602. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81603. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81604. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81605. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81606. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81607. vertex = new Vertex(position, normal, uv);
  81608. vertices.push(vertex);
  81609. }
  81610. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81611. // To handle the case of degenerated triangle
  81612. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81613. if (polygon.plane)
  81614. polygons.push(polygon);
  81615. }
  81616. }
  81617. var csg = CSG.FromPolygons(polygons);
  81618. csg.matrix = matrix;
  81619. csg.position = meshPosition;
  81620. csg.rotation = meshRotation;
  81621. csg.scaling = meshScaling;
  81622. csg.rotationQuaternion = meshRotationQuaternion;
  81623. currentCSGMeshId++;
  81624. return csg;
  81625. };
  81626. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81627. CSG.FromPolygons = function (polygons) {
  81628. var csg = new CSG();
  81629. csg.polygons = polygons;
  81630. return csg;
  81631. };
  81632. CSG.prototype.clone = function () {
  81633. var csg = new CSG();
  81634. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81635. csg.copyTransformAttributes(this);
  81636. return csg;
  81637. };
  81638. CSG.prototype.union = function (csg) {
  81639. var a = new Node(this.clone().polygons);
  81640. var b = new Node(csg.clone().polygons);
  81641. a.clipTo(b);
  81642. b.clipTo(a);
  81643. b.invert();
  81644. b.clipTo(a);
  81645. b.invert();
  81646. a.build(b.allPolygons());
  81647. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81648. };
  81649. CSG.prototype.unionInPlace = function (csg) {
  81650. var a = new Node(this.polygons);
  81651. var b = new Node(csg.polygons);
  81652. a.clipTo(b);
  81653. b.clipTo(a);
  81654. b.invert();
  81655. b.clipTo(a);
  81656. b.invert();
  81657. a.build(b.allPolygons());
  81658. this.polygons = a.allPolygons();
  81659. };
  81660. CSG.prototype.subtract = function (csg) {
  81661. var a = new Node(this.clone().polygons);
  81662. var b = new Node(csg.clone().polygons);
  81663. a.invert();
  81664. a.clipTo(b);
  81665. b.clipTo(a);
  81666. b.invert();
  81667. b.clipTo(a);
  81668. b.invert();
  81669. a.build(b.allPolygons());
  81670. a.invert();
  81671. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81672. };
  81673. CSG.prototype.subtractInPlace = function (csg) {
  81674. var a = new Node(this.polygons);
  81675. var b = new Node(csg.polygons);
  81676. a.invert();
  81677. a.clipTo(b);
  81678. b.clipTo(a);
  81679. b.invert();
  81680. b.clipTo(a);
  81681. b.invert();
  81682. a.build(b.allPolygons());
  81683. a.invert();
  81684. this.polygons = a.allPolygons();
  81685. };
  81686. CSG.prototype.intersect = function (csg) {
  81687. var a = new Node(this.clone().polygons);
  81688. var b = new Node(csg.clone().polygons);
  81689. a.invert();
  81690. b.clipTo(a);
  81691. b.invert();
  81692. a.clipTo(b);
  81693. b.clipTo(a);
  81694. a.build(b.allPolygons());
  81695. a.invert();
  81696. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81697. };
  81698. CSG.prototype.intersectInPlace = function (csg) {
  81699. var a = new Node(this.polygons);
  81700. var b = new Node(csg.polygons);
  81701. a.invert();
  81702. b.clipTo(a);
  81703. b.invert();
  81704. a.clipTo(b);
  81705. b.clipTo(a);
  81706. a.build(b.allPolygons());
  81707. a.invert();
  81708. this.polygons = a.allPolygons();
  81709. };
  81710. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81711. // not modified.
  81712. CSG.prototype.inverse = function () {
  81713. var csg = this.clone();
  81714. csg.inverseInPlace();
  81715. return csg;
  81716. };
  81717. CSG.prototype.inverseInPlace = function () {
  81718. this.polygons.map(function (p) { p.flip(); });
  81719. };
  81720. // This is used to keep meshes transformations so they can be restored
  81721. // when we build back a Babylon Mesh
  81722. // NB : All CSG operations are performed in world coordinates
  81723. CSG.prototype.copyTransformAttributes = function (csg) {
  81724. this.matrix = csg.matrix;
  81725. this.position = csg.position;
  81726. this.rotation = csg.rotation;
  81727. this.scaling = csg.scaling;
  81728. this.rotationQuaternion = csg.rotationQuaternion;
  81729. return this;
  81730. };
  81731. // Build Raw mesh from CSG
  81732. // Coordinates here are in world space
  81733. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81734. var matrix = this.matrix.clone();
  81735. matrix.invert();
  81736. 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;
  81737. if (keepSubMeshes) {
  81738. // Sort Polygons, since subMeshes are indices range
  81739. polygons.sort(function (a, b) {
  81740. if (a.shared.meshId === b.shared.meshId) {
  81741. return a.shared.subMeshId - b.shared.subMeshId;
  81742. }
  81743. else {
  81744. return a.shared.meshId - b.shared.meshId;
  81745. }
  81746. });
  81747. }
  81748. for (var i = 0, il = polygons.length; i < il; i++) {
  81749. polygon = polygons[i];
  81750. // Building SubMeshes
  81751. if (!subMesh_dict[polygon.shared.meshId]) {
  81752. subMesh_dict[polygon.shared.meshId] = {};
  81753. }
  81754. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81755. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81756. indexStart: +Infinity,
  81757. indexEnd: -Infinity,
  81758. materialIndex: polygon.shared.materialIndex
  81759. };
  81760. }
  81761. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81762. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81763. polygonIndices[0] = 0;
  81764. polygonIndices[1] = j - 1;
  81765. polygonIndices[2] = j;
  81766. for (var k = 0; k < 3; k++) {
  81767. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81768. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81769. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81770. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81771. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81772. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81773. // Check if 2 points can be merged
  81774. if (!(typeof vertex_idx !== 'undefined' &&
  81775. normals[vertex_idx * 3] === localNormal.x &&
  81776. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81777. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81778. uvs[vertex_idx * 2] === uv.x &&
  81779. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81780. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81781. uvs.push(uv.x, uv.y);
  81782. normals.push(normal.x, normal.y, normal.z);
  81783. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81784. }
  81785. indices.push(vertex_idx);
  81786. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81787. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81788. currentIndex++;
  81789. }
  81790. }
  81791. }
  81792. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81793. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81794. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81795. mesh.setIndices(indices, null);
  81796. if (keepSubMeshes) {
  81797. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81798. var materialIndexOffset = 0, materialMaxIndex;
  81799. mesh.subMeshes = new Array();
  81800. for (var m in subMesh_dict) {
  81801. materialMaxIndex = -1;
  81802. for (var sm in subMesh_dict[m]) {
  81803. subMesh_obj = subMesh_dict[m][sm];
  81804. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81805. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81806. }
  81807. materialIndexOffset += ++materialMaxIndex;
  81808. }
  81809. }
  81810. return mesh;
  81811. };
  81812. // Build Mesh from CSG taking material and transforms into account
  81813. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81814. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81815. mesh.material = material;
  81816. mesh.position.copyFrom(this.position);
  81817. mesh.rotation.copyFrom(this.rotation);
  81818. if (this.rotationQuaternion) {
  81819. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81820. }
  81821. mesh.scaling.copyFrom(this.scaling);
  81822. mesh.computeWorldMatrix(true);
  81823. return mesh;
  81824. };
  81825. return CSG;
  81826. }());
  81827. BABYLON.CSG = CSG;
  81828. })(BABYLON || (BABYLON = {}));
  81829. //# sourceMappingURL=babylon.csg.js.map
  81830. var BABYLON;
  81831. (function (BABYLON) {
  81832. var LensFlare = /** @class */ (function () {
  81833. function LensFlare(size, position, color, imgUrl, system) {
  81834. this.size = size;
  81835. this.position = position;
  81836. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81837. this.color = color || new BABYLON.Color3(1, 1, 1);
  81838. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81839. this._system = system;
  81840. system.lensFlares.push(this);
  81841. }
  81842. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81843. return new LensFlare(size, position, color, imgUrl, system);
  81844. };
  81845. LensFlare.prototype.dispose = function () {
  81846. if (this.texture) {
  81847. this.texture.dispose();
  81848. }
  81849. // Remove from scene
  81850. var index = this._system.lensFlares.indexOf(this);
  81851. this._system.lensFlares.splice(index, 1);
  81852. };
  81853. ;
  81854. return LensFlare;
  81855. }());
  81856. BABYLON.LensFlare = LensFlare;
  81857. })(BABYLON || (BABYLON = {}));
  81858. //# sourceMappingURL=babylon.lensFlare.js.map
  81859. var BABYLON;
  81860. (function (BABYLON) {
  81861. var LensFlareSystem = /** @class */ (function () {
  81862. function LensFlareSystem(name, emitter, scene) {
  81863. this.name = name;
  81864. this.lensFlares = new Array();
  81865. this.borderLimit = 300;
  81866. this.viewportBorder = 0;
  81867. this.layerMask = 0x0FFFFFFF;
  81868. this._vertexBuffers = {};
  81869. this._isEnabled = true;
  81870. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81871. this._emitter = emitter;
  81872. this.id = name;
  81873. scene.lensFlareSystems.push(this);
  81874. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81875. var engine = scene.getEngine();
  81876. // VBO
  81877. var vertices = [];
  81878. vertices.push(1, 1);
  81879. vertices.push(-1, 1);
  81880. vertices.push(-1, -1);
  81881. vertices.push(1, -1);
  81882. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81883. // Indices
  81884. var indices = [];
  81885. indices.push(0);
  81886. indices.push(1);
  81887. indices.push(2);
  81888. indices.push(0);
  81889. indices.push(2);
  81890. indices.push(3);
  81891. this._indexBuffer = engine.createIndexBuffer(indices);
  81892. // Effects
  81893. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81894. }
  81895. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81896. get: function () {
  81897. return this._isEnabled;
  81898. },
  81899. set: function (value) {
  81900. this._isEnabled = value;
  81901. },
  81902. enumerable: true,
  81903. configurable: true
  81904. });
  81905. LensFlareSystem.prototype.getScene = function () {
  81906. return this._scene;
  81907. };
  81908. LensFlareSystem.prototype.getEmitter = function () {
  81909. return this._emitter;
  81910. };
  81911. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81912. this._emitter = newEmitter;
  81913. };
  81914. LensFlareSystem.prototype.getEmitterPosition = function () {
  81915. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81916. };
  81917. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81918. var position = this.getEmitterPosition();
  81919. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81920. this._positionX = position.x;
  81921. this._positionY = position.y;
  81922. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81923. if (this.viewportBorder > 0) {
  81924. globalViewport.x -= this.viewportBorder;
  81925. globalViewport.y -= this.viewportBorder;
  81926. globalViewport.width += this.viewportBorder * 2;
  81927. globalViewport.height += this.viewportBorder * 2;
  81928. position.x += this.viewportBorder;
  81929. position.y += this.viewportBorder;
  81930. this._positionX += this.viewportBorder;
  81931. this._positionY += this.viewportBorder;
  81932. }
  81933. if (position.z > 0) {
  81934. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81935. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81936. return true;
  81937. }
  81938. return true;
  81939. }
  81940. return false;
  81941. };
  81942. LensFlareSystem.prototype._isVisible = function () {
  81943. if (!this._isEnabled || !this._scene.activeCamera) {
  81944. return false;
  81945. }
  81946. var emitterPosition = this.getEmitterPosition();
  81947. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81948. var distance = direction.length();
  81949. direction.normalize();
  81950. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81951. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81952. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81953. };
  81954. LensFlareSystem.prototype.render = function () {
  81955. if (!this._effect.isReady() || !this._scene.activeCamera)
  81956. return false;
  81957. var engine = this._scene.getEngine();
  81958. var viewport = this._scene.activeCamera.viewport;
  81959. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81960. // Position
  81961. if (!this.computeEffectivePosition(globalViewport)) {
  81962. return false;
  81963. }
  81964. // Visibility
  81965. if (!this._isVisible()) {
  81966. return false;
  81967. }
  81968. // Intensity
  81969. var awayX;
  81970. var awayY;
  81971. if (this._positionX < this.borderLimit + globalViewport.x) {
  81972. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81973. }
  81974. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81975. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81976. }
  81977. else {
  81978. awayX = 0;
  81979. }
  81980. if (this._positionY < this.borderLimit + globalViewport.y) {
  81981. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81982. }
  81983. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81984. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81985. }
  81986. else {
  81987. awayY = 0;
  81988. }
  81989. var away = (awayX > awayY) ? awayX : awayY;
  81990. away -= this.viewportBorder;
  81991. if (away > this.borderLimit) {
  81992. away = this.borderLimit;
  81993. }
  81994. var intensity = 1.0 - (away / this.borderLimit);
  81995. if (intensity < 0) {
  81996. return false;
  81997. }
  81998. if (intensity > 1.0) {
  81999. intensity = 1.0;
  82000. }
  82001. if (this.viewportBorder > 0) {
  82002. globalViewport.x += this.viewportBorder;
  82003. globalViewport.y += this.viewportBorder;
  82004. globalViewport.width -= this.viewportBorder * 2;
  82005. globalViewport.height -= this.viewportBorder * 2;
  82006. this._positionX -= this.viewportBorder;
  82007. this._positionY -= this.viewportBorder;
  82008. }
  82009. // Position
  82010. var centerX = globalViewport.x + globalViewport.width / 2;
  82011. var centerY = globalViewport.y + globalViewport.height / 2;
  82012. var distX = centerX - this._positionX;
  82013. var distY = centerY - this._positionY;
  82014. // Effects
  82015. engine.enableEffect(this._effect);
  82016. engine.setState(false);
  82017. engine.setDepthBuffer(false);
  82018. // VBOs
  82019. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82020. // Flares
  82021. for (var index = 0; index < this.lensFlares.length; index++) {
  82022. var flare = this.lensFlares[index];
  82023. engine.setAlphaMode(flare.alphaMode);
  82024. var x = centerX - (distX * flare.position);
  82025. var y = centerY - (distY * flare.position);
  82026. var cw = flare.size;
  82027. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82028. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82029. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82030. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82031. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82032. // Texture
  82033. this._effect.setTexture("textureSampler", flare.texture);
  82034. // Color
  82035. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82036. // Draw order
  82037. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82038. }
  82039. engine.setDepthBuffer(true);
  82040. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82041. return true;
  82042. };
  82043. LensFlareSystem.prototype.dispose = function () {
  82044. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82045. if (vertexBuffer) {
  82046. vertexBuffer.dispose();
  82047. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82048. }
  82049. if (this._indexBuffer) {
  82050. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82051. this._indexBuffer = null;
  82052. }
  82053. while (this.lensFlares.length) {
  82054. this.lensFlares[0].dispose();
  82055. }
  82056. // Remove from scene
  82057. var index = this._scene.lensFlareSystems.indexOf(this);
  82058. this._scene.lensFlareSystems.splice(index, 1);
  82059. };
  82060. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82061. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82062. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82063. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82064. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82065. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82066. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82067. var parsedFlare = parsedLensFlareSystem.flares[index];
  82068. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82069. }
  82070. return lensFlareSystem;
  82071. };
  82072. LensFlareSystem.prototype.serialize = function () {
  82073. var serializationObject = {};
  82074. serializationObject.id = this.id;
  82075. serializationObject.name = this.name;
  82076. serializationObject.emitterId = this.getEmitter().id;
  82077. serializationObject.borderLimit = this.borderLimit;
  82078. serializationObject.flares = [];
  82079. for (var index = 0; index < this.lensFlares.length; index++) {
  82080. var flare = this.lensFlares[index];
  82081. serializationObject.flares.push({
  82082. size: flare.size,
  82083. position: flare.position,
  82084. color: flare.color.asArray(),
  82085. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82086. });
  82087. }
  82088. return serializationObject;
  82089. };
  82090. return LensFlareSystem;
  82091. }());
  82092. BABYLON.LensFlareSystem = LensFlareSystem;
  82093. })(BABYLON || (BABYLON = {}));
  82094. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82095. var BABYLON;
  82096. (function (BABYLON) {
  82097. /**
  82098. * This is a holder class for the physics joint created by the physics plugin.
  82099. * It holds a set of functions to control the underlying joint.
  82100. */
  82101. var PhysicsJoint = /** @class */ (function () {
  82102. function PhysicsJoint(type, jointData) {
  82103. this.type = type;
  82104. this.jointData = jointData;
  82105. jointData.nativeParams = jointData.nativeParams || {};
  82106. }
  82107. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82108. get: function () {
  82109. return this._physicsJoint;
  82110. },
  82111. set: function (newJoint) {
  82112. if (this._physicsJoint) {
  82113. //remove from the wolrd
  82114. }
  82115. this._physicsJoint = newJoint;
  82116. },
  82117. enumerable: true,
  82118. configurable: true
  82119. });
  82120. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82121. set: function (physicsPlugin) {
  82122. this._physicsPlugin = physicsPlugin;
  82123. },
  82124. enumerable: true,
  82125. configurable: true
  82126. });
  82127. /**
  82128. * Execute a function that is physics-plugin specific.
  82129. * @param {Function} func the function that will be executed.
  82130. * It accepts two parameters: the physics world and the physics joint.
  82131. */
  82132. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82133. func(this._physicsPlugin.world, this._physicsJoint);
  82134. };
  82135. //TODO check if the native joints are the same
  82136. //Joint Types
  82137. PhysicsJoint.DistanceJoint = 0;
  82138. PhysicsJoint.HingeJoint = 1;
  82139. PhysicsJoint.BallAndSocketJoint = 2;
  82140. PhysicsJoint.WheelJoint = 3;
  82141. PhysicsJoint.SliderJoint = 4;
  82142. //OIMO
  82143. PhysicsJoint.PrismaticJoint = 5;
  82144. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82145. PhysicsJoint.UniversalJoint = 6;
  82146. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82147. //Cannon
  82148. //Similar to a Ball-Joint. Different in params
  82149. PhysicsJoint.PointToPointJoint = 8;
  82150. //Cannon only at the moment
  82151. PhysicsJoint.SpringJoint = 9;
  82152. PhysicsJoint.LockJoint = 10;
  82153. return PhysicsJoint;
  82154. }());
  82155. BABYLON.PhysicsJoint = PhysicsJoint;
  82156. /**
  82157. * A class representing a physics distance joint.
  82158. */
  82159. var DistanceJoint = /** @class */ (function (_super) {
  82160. __extends(DistanceJoint, _super);
  82161. function DistanceJoint(jointData) {
  82162. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82163. }
  82164. /**
  82165. * Update the predefined distance.
  82166. */
  82167. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82168. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82169. };
  82170. return DistanceJoint;
  82171. }(PhysicsJoint));
  82172. BABYLON.DistanceJoint = DistanceJoint;
  82173. var MotorEnabledJoint = /** @class */ (function (_super) {
  82174. __extends(MotorEnabledJoint, _super);
  82175. function MotorEnabledJoint(type, jointData) {
  82176. return _super.call(this, type, jointData) || this;
  82177. }
  82178. /**
  82179. * Set the motor values.
  82180. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82181. * @param {number} force the force to apply
  82182. * @param {number} maxForce max force for this motor.
  82183. */
  82184. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82185. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82186. };
  82187. /**
  82188. * Set the motor's limits.
  82189. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82190. */
  82191. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82192. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82193. };
  82194. return MotorEnabledJoint;
  82195. }(PhysicsJoint));
  82196. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82197. /**
  82198. * This class represents a single hinge physics joint
  82199. */
  82200. var HingeJoint = /** @class */ (function (_super) {
  82201. __extends(HingeJoint, _super);
  82202. function HingeJoint(jointData) {
  82203. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82204. }
  82205. /**
  82206. * Set the motor values.
  82207. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82208. * @param {number} force the force to apply
  82209. * @param {number} maxForce max force for this motor.
  82210. */
  82211. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82212. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82213. };
  82214. /**
  82215. * Set the motor's limits.
  82216. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82217. */
  82218. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82219. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82220. };
  82221. return HingeJoint;
  82222. }(MotorEnabledJoint));
  82223. BABYLON.HingeJoint = HingeJoint;
  82224. /**
  82225. * This class represents a dual hinge physics joint (same as wheel joint)
  82226. */
  82227. var Hinge2Joint = /** @class */ (function (_super) {
  82228. __extends(Hinge2Joint, _super);
  82229. function Hinge2Joint(jointData) {
  82230. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82231. }
  82232. /**
  82233. * Set the motor values.
  82234. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82235. * @param {number} force the force to apply
  82236. * @param {number} maxForce max force for this motor.
  82237. * @param {motorIndex} the motor's index, 0 or 1.
  82238. */
  82239. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82240. if (motorIndex === void 0) { motorIndex = 0; }
  82241. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82242. };
  82243. /**
  82244. * Set the motor limits.
  82245. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82246. * @param {number} upperLimit the upper limit
  82247. * @param {number} lowerLimit lower limit
  82248. * @param {motorIndex} the motor's index, 0 or 1.
  82249. */
  82250. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82251. if (motorIndex === void 0) { motorIndex = 0; }
  82252. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82253. };
  82254. return Hinge2Joint;
  82255. }(MotorEnabledJoint));
  82256. BABYLON.Hinge2Joint = Hinge2Joint;
  82257. })(BABYLON || (BABYLON = {}));
  82258. //# sourceMappingURL=babylon.physicsJoint.js.map
  82259. var BABYLON;
  82260. (function (BABYLON) {
  82261. var PhysicsImpostor = /** @class */ (function () {
  82262. function PhysicsImpostor(object, type, _options, _scene) {
  82263. if (_options === void 0) { _options = { mass: 0 }; }
  82264. var _this = this;
  82265. this.object = object;
  82266. this.type = type;
  82267. this._options = _options;
  82268. this._scene = _scene;
  82269. this._bodyUpdateRequired = false;
  82270. this._onBeforePhysicsStepCallbacks = new Array();
  82271. this._onAfterPhysicsStepCallbacks = new Array();
  82272. this._onPhysicsCollideCallbacks = [];
  82273. this._deltaPosition = BABYLON.Vector3.Zero();
  82274. this._isDisposed = false;
  82275. //temp variables for parent rotation calculations
  82276. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82277. this._tmpQuat = new BABYLON.Quaternion();
  82278. this._tmpQuat2 = new BABYLON.Quaternion();
  82279. /**
  82280. * this function is executed by the physics engine.
  82281. */
  82282. this.beforeStep = function () {
  82283. if (!_this._physicsEngine) {
  82284. return;
  82285. }
  82286. _this.object.translate(_this._deltaPosition, -1);
  82287. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82288. _this.object.computeWorldMatrix(false);
  82289. if (_this.object.parent && _this.object.rotationQuaternion) {
  82290. _this.getParentsRotation();
  82291. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82292. }
  82293. else {
  82294. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82295. }
  82296. if (!_this._options.disableBidirectionalTransformation) {
  82297. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82298. }
  82299. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82300. func(_this);
  82301. });
  82302. };
  82303. /**
  82304. * this function is executed by the physics engine.
  82305. */
  82306. this.afterStep = function () {
  82307. if (!_this._physicsEngine) {
  82308. return;
  82309. }
  82310. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82311. func(_this);
  82312. });
  82313. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82314. // object has now its world rotation. needs to be converted to local.
  82315. if (_this.object.parent && _this.object.rotationQuaternion) {
  82316. _this.getParentsRotation();
  82317. _this._tmpQuat.conjugateInPlace();
  82318. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82319. }
  82320. // take the position set and make it the absolute position of this object.
  82321. _this.object.setAbsolutePosition(_this.object.position);
  82322. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82323. _this.object.translate(_this._deltaPosition, 1);
  82324. };
  82325. /**
  82326. * Legacy collision detection event support
  82327. */
  82328. this.onCollideEvent = null;
  82329. //event and body object due to cannon's event-based architecture.
  82330. this.onCollide = function (e) {
  82331. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82332. return;
  82333. }
  82334. if (!_this._physicsEngine) {
  82335. return;
  82336. }
  82337. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82338. if (otherImpostor) {
  82339. // Legacy collision detection event support
  82340. if (_this.onCollideEvent) {
  82341. _this.onCollideEvent(_this, otherImpostor);
  82342. }
  82343. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82344. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82345. }).forEach(function (obj) {
  82346. obj.callback(_this, otherImpostor);
  82347. });
  82348. }
  82349. };
  82350. //sanity check!
  82351. if (!this.object) {
  82352. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82353. return;
  82354. }
  82355. //legacy support for old syntax.
  82356. if (!this._scene && object.getScene) {
  82357. this._scene = object.getScene();
  82358. }
  82359. if (!this._scene) {
  82360. return;
  82361. }
  82362. this._physicsEngine = this._scene.getPhysicsEngine();
  82363. if (!this._physicsEngine) {
  82364. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82365. }
  82366. else {
  82367. //set the object's quaternion, if not set
  82368. if (!this.object.rotationQuaternion) {
  82369. if (this.object.rotation) {
  82370. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82371. }
  82372. else {
  82373. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82374. }
  82375. }
  82376. //default options params
  82377. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82378. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82379. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82380. this._joints = [];
  82381. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82382. if (!this.object.parent || this._options.ignoreParent) {
  82383. this._init();
  82384. }
  82385. else if (this.object.parent.physicsImpostor) {
  82386. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82387. }
  82388. }
  82389. }
  82390. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82391. get: function () {
  82392. return this._isDisposed;
  82393. },
  82394. enumerable: true,
  82395. configurable: true
  82396. });
  82397. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82398. get: function () {
  82399. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82400. },
  82401. set: function (value) {
  82402. this.setMass(value);
  82403. },
  82404. enumerable: true,
  82405. configurable: true
  82406. });
  82407. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82408. get: function () {
  82409. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82410. },
  82411. set: function (value) {
  82412. if (!this._physicsEngine) {
  82413. return;
  82414. }
  82415. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82416. },
  82417. enumerable: true,
  82418. configurable: true
  82419. });
  82420. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82421. get: function () {
  82422. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82423. },
  82424. set: function (value) {
  82425. if (!this._physicsEngine) {
  82426. return;
  82427. }
  82428. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82429. },
  82430. enumerable: true,
  82431. configurable: true
  82432. });
  82433. /**
  82434. * This function will completly initialize this impostor.
  82435. * It will create a new body - but only if this mesh has no parent.
  82436. * If it has, this impostor will not be used other than to define the impostor
  82437. * of the child mesh.
  82438. */
  82439. PhysicsImpostor.prototype._init = function () {
  82440. if (!this._physicsEngine) {
  82441. return;
  82442. }
  82443. this._physicsEngine.removeImpostor(this);
  82444. this.physicsBody = null;
  82445. this._parent = this._parent || this._getPhysicsParent();
  82446. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82447. this._physicsEngine.addImpostor(this);
  82448. }
  82449. };
  82450. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82451. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82452. var parentMesh = this.object.parent;
  82453. return parentMesh.physicsImpostor;
  82454. }
  82455. return null;
  82456. };
  82457. /**
  82458. * Should a new body be generated.
  82459. */
  82460. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82461. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82462. };
  82463. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82464. this.forceUpdate();
  82465. };
  82466. /**
  82467. * Force a regeneration of this or the parent's impostor's body.
  82468. * Use under cautious - This will remove all joints already implemented.
  82469. */
  82470. PhysicsImpostor.prototype.forceUpdate = function () {
  82471. this._init();
  82472. if (this.parent && !this._options.ignoreParent) {
  82473. this.parent.forceUpdate();
  82474. }
  82475. };
  82476. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82477. /*public get mesh(): AbstractMesh {
  82478. return this._mesh;
  82479. }*/
  82480. /**
  82481. * Gets the body that holds this impostor. Either its own, or its parent.
  82482. */
  82483. get: function () {
  82484. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82485. },
  82486. /**
  82487. * Set the physics body. Used mainly by the physics engine/plugin
  82488. */
  82489. set: function (physicsBody) {
  82490. if (this._physicsBody && this._physicsEngine) {
  82491. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82492. }
  82493. this._physicsBody = physicsBody;
  82494. this.resetUpdateFlags();
  82495. },
  82496. enumerable: true,
  82497. configurable: true
  82498. });
  82499. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82500. get: function () {
  82501. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82502. },
  82503. set: function (value) {
  82504. this._parent = value;
  82505. },
  82506. enumerable: true,
  82507. configurable: true
  82508. });
  82509. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82510. this._bodyUpdateRequired = false;
  82511. };
  82512. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82513. if (this.object.getBoundingInfo) {
  82514. var q = this.object.rotationQuaternion;
  82515. //reset rotation
  82516. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82517. //calculate the world matrix with no rotation
  82518. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82519. var boundingInfo = this.object.getBoundingInfo();
  82520. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82521. //bring back the rotation
  82522. this.object.rotationQuaternion = q;
  82523. //calculate the world matrix with the new rotation
  82524. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82525. return size;
  82526. }
  82527. else {
  82528. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82529. }
  82530. };
  82531. PhysicsImpostor.prototype.getObjectCenter = function () {
  82532. if (this.object.getBoundingInfo) {
  82533. var boundingInfo = this.object.getBoundingInfo();
  82534. return boundingInfo.boundingBox.centerWorld;
  82535. }
  82536. else {
  82537. return this.object.position;
  82538. }
  82539. };
  82540. /**
  82541. * Get a specific parametes from the options parameter.
  82542. */
  82543. PhysicsImpostor.prototype.getParam = function (paramName) {
  82544. return this._options[paramName];
  82545. };
  82546. /**
  82547. * Sets a specific parameter in the options given to the physics plugin
  82548. */
  82549. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82550. this._options[paramName] = value;
  82551. this._bodyUpdateRequired = true;
  82552. };
  82553. /**
  82554. * Specifically change the body's mass option. Won't recreate the physics body object
  82555. */
  82556. PhysicsImpostor.prototype.setMass = function (mass) {
  82557. if (this.getParam("mass") !== mass) {
  82558. this.setParam("mass", mass);
  82559. }
  82560. if (this._physicsEngine) {
  82561. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82562. }
  82563. };
  82564. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82565. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82566. };
  82567. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82568. if (this._physicsEngine) {
  82569. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82570. }
  82571. };
  82572. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82573. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82574. };
  82575. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82576. if (this._physicsEngine) {
  82577. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82578. }
  82579. };
  82580. /**
  82581. * Execute a function with the physics plugin native code.
  82582. * Provide a function the will have two variables - the world object and the physics body object.
  82583. */
  82584. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82585. if (this._physicsEngine) {
  82586. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82587. }
  82588. };
  82589. /**
  82590. * Register a function that will be executed before the physics world is stepping forward.
  82591. */
  82592. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82593. this._onBeforePhysicsStepCallbacks.push(func);
  82594. };
  82595. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82596. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82597. if (index > -1) {
  82598. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82599. }
  82600. else {
  82601. BABYLON.Tools.Warn("Function to remove was not found");
  82602. }
  82603. };
  82604. /**
  82605. * Register a function that will be executed after the physics step
  82606. */
  82607. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82608. this._onAfterPhysicsStepCallbacks.push(func);
  82609. };
  82610. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82611. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82612. if (index > -1) {
  82613. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82614. }
  82615. else {
  82616. BABYLON.Tools.Warn("Function to remove was not found");
  82617. }
  82618. };
  82619. /**
  82620. * register a function that will be executed when this impostor collides against a different body.
  82621. */
  82622. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82623. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82624. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82625. };
  82626. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82627. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82628. var index = -1;
  82629. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82630. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82631. // chcek the arrays match
  82632. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82633. return collidedAgainstList.indexOf(impostor) > -1;
  82634. });
  82635. if (sameList) {
  82636. index = idx;
  82637. }
  82638. return sameList;
  82639. }
  82640. return false;
  82641. });
  82642. if (found) {
  82643. this._onPhysicsCollideCallbacks.splice(index, 1);
  82644. }
  82645. else {
  82646. BABYLON.Tools.Warn("Function to remove was not found");
  82647. }
  82648. };
  82649. PhysicsImpostor.prototype.getParentsRotation = function () {
  82650. var parent = this.object.parent;
  82651. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82652. while (parent) {
  82653. if (parent.rotationQuaternion) {
  82654. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82655. }
  82656. else {
  82657. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82658. }
  82659. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82660. parent = parent.parent;
  82661. }
  82662. return this._tmpQuat;
  82663. };
  82664. /**
  82665. * Apply a force
  82666. */
  82667. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82668. if (this._physicsEngine) {
  82669. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82670. }
  82671. return this;
  82672. };
  82673. /**
  82674. * Apply an impulse
  82675. */
  82676. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82677. if (this._physicsEngine) {
  82678. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82679. }
  82680. return this;
  82681. };
  82682. /**
  82683. * A help function to create a joint.
  82684. */
  82685. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82686. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82687. this.addJoint(otherImpostor, joint);
  82688. return this;
  82689. };
  82690. /**
  82691. * Add a joint to this impostor with a different impostor.
  82692. */
  82693. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82694. this._joints.push({
  82695. otherImpostor: otherImpostor,
  82696. joint: joint
  82697. });
  82698. if (this._physicsEngine) {
  82699. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82700. }
  82701. return this;
  82702. };
  82703. /**
  82704. * Will keep this body still, in a sleep mode.
  82705. */
  82706. PhysicsImpostor.prototype.sleep = function () {
  82707. if (this._physicsEngine) {
  82708. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82709. }
  82710. return this;
  82711. };
  82712. /**
  82713. * Wake the body up.
  82714. */
  82715. PhysicsImpostor.prototype.wakeUp = function () {
  82716. if (this._physicsEngine) {
  82717. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82718. }
  82719. return this;
  82720. };
  82721. PhysicsImpostor.prototype.clone = function (newObject) {
  82722. if (!newObject)
  82723. return null;
  82724. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82725. };
  82726. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82727. var _this = this;
  82728. //no dispose if no physics engine is available.
  82729. if (!this._physicsEngine) {
  82730. return;
  82731. }
  82732. this._joints.forEach(function (j) {
  82733. if (_this._physicsEngine) {
  82734. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82735. }
  82736. });
  82737. //dispose the physics body
  82738. this._physicsEngine.removeImpostor(this);
  82739. if (this.parent) {
  82740. this.parent.forceUpdate();
  82741. }
  82742. else {
  82743. /*this._object.getChildMeshes().forEach(function(mesh) {
  82744. if (mesh.physicsImpostor) {
  82745. if (disposeChildren) {
  82746. mesh.physicsImpostor.dispose();
  82747. mesh.physicsImpostor = null;
  82748. }
  82749. }
  82750. })*/
  82751. }
  82752. this._isDisposed = true;
  82753. };
  82754. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82755. this._deltaPosition.copyFrom(position);
  82756. };
  82757. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82758. if (!this._deltaRotation) {
  82759. this._deltaRotation = new BABYLON.Quaternion();
  82760. }
  82761. this._deltaRotation.copyFrom(rotation);
  82762. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82763. };
  82764. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82765. if (this._physicsEngine) {
  82766. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82767. }
  82768. return this;
  82769. };
  82770. PhysicsImpostor.prototype.getRadius = function () {
  82771. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82772. };
  82773. /**
  82774. * Sync a bone with this impostor
  82775. * @param bone The bone to sync to the impostor.
  82776. * @param boneMesh The mesh that the bone is influencing.
  82777. * @param jointPivot The pivot of the joint / bone in local space.
  82778. * @param distToJoint Optional distance from the impostor to the joint.
  82779. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82780. */
  82781. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82782. var tempVec = PhysicsImpostor._tmpVecs[0];
  82783. var mesh = this.object;
  82784. if (mesh.rotationQuaternion) {
  82785. if (adjustRotation) {
  82786. var tempQuat = PhysicsImpostor._tmpQuat;
  82787. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82788. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82789. }
  82790. else {
  82791. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82792. }
  82793. }
  82794. tempVec.x = 0;
  82795. tempVec.y = 0;
  82796. tempVec.z = 0;
  82797. if (jointPivot) {
  82798. tempVec.x = jointPivot.x;
  82799. tempVec.y = jointPivot.y;
  82800. tempVec.z = jointPivot.z;
  82801. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82802. if (distToJoint === undefined || distToJoint === null) {
  82803. distToJoint = jointPivot.length();
  82804. }
  82805. tempVec.x *= distToJoint;
  82806. tempVec.y *= distToJoint;
  82807. tempVec.z *= distToJoint;
  82808. }
  82809. if (bone.getParent()) {
  82810. tempVec.addInPlace(mesh.getAbsolutePosition());
  82811. bone.setAbsolutePosition(tempVec, boneMesh);
  82812. }
  82813. else {
  82814. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82815. boneMesh.position.x -= tempVec.x;
  82816. boneMesh.position.y -= tempVec.y;
  82817. boneMesh.position.z -= tempVec.z;
  82818. }
  82819. };
  82820. /**
  82821. * Sync impostor to a bone
  82822. * @param bone The bone that the impostor will be synced to.
  82823. * @param boneMesh The mesh that the bone is influencing.
  82824. * @param jointPivot The pivot of the joint / bone in local space.
  82825. * @param distToJoint Optional distance from the impostor to the joint.
  82826. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82827. * @param boneAxis Optional vector3 axis the bone is aligned with
  82828. */
  82829. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82830. var mesh = this.object;
  82831. if (mesh.rotationQuaternion) {
  82832. if (adjustRotation) {
  82833. var tempQuat = PhysicsImpostor._tmpQuat;
  82834. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82835. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82836. }
  82837. else {
  82838. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82839. }
  82840. }
  82841. var pos = PhysicsImpostor._tmpVecs[0];
  82842. var boneDir = PhysicsImpostor._tmpVecs[1];
  82843. if (!boneAxis) {
  82844. boneAxis = PhysicsImpostor._tmpVecs[2];
  82845. boneAxis.x = 0;
  82846. boneAxis.y = 1;
  82847. boneAxis.z = 0;
  82848. }
  82849. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82850. bone.getAbsolutePositionToRef(boneMesh, pos);
  82851. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82852. distToJoint = jointPivot.length();
  82853. }
  82854. if (distToJoint !== undefined && distToJoint !== null) {
  82855. pos.x += boneDir.x * distToJoint;
  82856. pos.y += boneDir.y * distToJoint;
  82857. pos.z += boneDir.z * distToJoint;
  82858. }
  82859. mesh.setAbsolutePosition(pos);
  82860. };
  82861. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82862. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82863. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82864. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82865. //Impostor types
  82866. PhysicsImpostor.NoImpostor = 0;
  82867. PhysicsImpostor.SphereImpostor = 1;
  82868. PhysicsImpostor.BoxImpostor = 2;
  82869. PhysicsImpostor.PlaneImpostor = 3;
  82870. PhysicsImpostor.MeshImpostor = 4;
  82871. PhysicsImpostor.CylinderImpostor = 7;
  82872. PhysicsImpostor.ParticleImpostor = 8;
  82873. PhysicsImpostor.HeightmapImpostor = 9;
  82874. return PhysicsImpostor;
  82875. }());
  82876. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82877. })(BABYLON || (BABYLON = {}));
  82878. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82879. var BABYLON;
  82880. (function (BABYLON) {
  82881. var PhysicsEngine = /** @class */ (function () {
  82882. function PhysicsEngine(gravity, _physicsPlugin) {
  82883. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82884. this._physicsPlugin = _physicsPlugin;
  82885. //new methods and parameters
  82886. this._impostors = [];
  82887. this._joints = [];
  82888. if (!this._physicsPlugin.isSupported()) {
  82889. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82890. + "Please make sure it is included.");
  82891. }
  82892. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82893. this.setGravity(gravity);
  82894. this.setTimeStep();
  82895. }
  82896. PhysicsEngine.prototype.setGravity = function (gravity) {
  82897. this.gravity = gravity;
  82898. this._physicsPlugin.setGravity(this.gravity);
  82899. };
  82900. /**
  82901. * Set the time step of the physics engine.
  82902. * default is 1/60.
  82903. * To slow it down, enter 1/600 for example.
  82904. * To speed it up, 1/30
  82905. * @param {number} newTimeStep the new timestep to apply to this world.
  82906. */
  82907. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82908. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82909. this._physicsPlugin.setTimeStep(newTimeStep);
  82910. };
  82911. /**
  82912. * Get the time step of the physics engine.
  82913. */
  82914. PhysicsEngine.prototype.getTimeStep = function () {
  82915. return this._physicsPlugin.getTimeStep();
  82916. };
  82917. PhysicsEngine.prototype.dispose = function () {
  82918. this._impostors.forEach(function (impostor) {
  82919. impostor.dispose();
  82920. });
  82921. this._physicsPlugin.dispose();
  82922. };
  82923. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82924. return this._physicsPlugin.name;
  82925. };
  82926. /**
  82927. * Adding a new impostor for the impostor tracking.
  82928. * This will be done by the impostor itself.
  82929. * @param {PhysicsImpostor} impostor the impostor to add
  82930. */
  82931. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82932. impostor.uniqueId = this._impostors.push(impostor);
  82933. //if no parent, generate the body
  82934. if (!impostor.parent) {
  82935. this._physicsPlugin.generatePhysicsBody(impostor);
  82936. }
  82937. };
  82938. /**
  82939. * Remove an impostor from the engine.
  82940. * This impostor and its mesh will not longer be updated by the physics engine.
  82941. * @param {PhysicsImpostor} impostor the impostor to remove
  82942. */
  82943. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82944. var index = this._impostors.indexOf(impostor);
  82945. if (index > -1) {
  82946. var removed = this._impostors.splice(index, 1);
  82947. //Is it needed?
  82948. if (removed.length) {
  82949. //this will also remove it from the world.
  82950. removed[0].physicsBody = null;
  82951. }
  82952. }
  82953. };
  82954. /**
  82955. * Add a joint to the physics engine
  82956. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82957. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82958. * @param {PhysicsJoint} the joint that will connect both impostors.
  82959. */
  82960. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82961. var impostorJoint = {
  82962. mainImpostor: mainImpostor,
  82963. connectedImpostor: connectedImpostor,
  82964. joint: joint
  82965. };
  82966. joint.physicsPlugin = this._physicsPlugin;
  82967. this._joints.push(impostorJoint);
  82968. this._physicsPlugin.generateJoint(impostorJoint);
  82969. };
  82970. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82971. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82972. return (impostorJoint.connectedImpostor === connectedImpostor
  82973. && impostorJoint.joint === joint
  82974. && impostorJoint.mainImpostor === mainImpostor);
  82975. });
  82976. if (matchingJoints.length) {
  82977. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82978. //TODO remove it from the list as well
  82979. }
  82980. };
  82981. /**
  82982. * Called by the scene. no need to call it.
  82983. */
  82984. PhysicsEngine.prototype._step = function (delta) {
  82985. var _this = this;
  82986. //check if any mesh has no body / requires an update
  82987. this._impostors.forEach(function (impostor) {
  82988. if (impostor.isBodyInitRequired()) {
  82989. _this._physicsPlugin.generatePhysicsBody(impostor);
  82990. }
  82991. });
  82992. if (delta > 0.1) {
  82993. delta = 0.1;
  82994. }
  82995. else if (delta <= 0) {
  82996. delta = 1.0 / 60.0;
  82997. }
  82998. this._physicsPlugin.executeStep(delta, this._impostors);
  82999. };
  83000. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83001. return this._physicsPlugin;
  83002. };
  83003. PhysicsEngine.prototype.getImpostors = function () {
  83004. return this._impostors;
  83005. };
  83006. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83007. for (var i = 0; i < this._impostors.length; ++i) {
  83008. if (this._impostors[i].object === object) {
  83009. return this._impostors[i];
  83010. }
  83011. }
  83012. return null;
  83013. };
  83014. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83015. for (var i = 0; i < this._impostors.length; ++i) {
  83016. if (this._impostors[i].physicsBody === body) {
  83017. return this._impostors[i];
  83018. }
  83019. }
  83020. return null;
  83021. };
  83022. // Statics
  83023. PhysicsEngine.Epsilon = 0.001;
  83024. return PhysicsEngine;
  83025. }());
  83026. BABYLON.PhysicsEngine = PhysicsEngine;
  83027. })(BABYLON || (BABYLON = {}));
  83028. //# sourceMappingURL=babylon.physicsEngine.js.map
  83029. var BABYLON;
  83030. (function (BABYLON) {
  83031. var PhysicsHelper = /** @class */ (function () {
  83032. function PhysicsHelper(scene) {
  83033. this._scene = scene;
  83034. this._physicsEngine = this._scene.getPhysicsEngine();
  83035. if (!this._physicsEngine) {
  83036. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83037. }
  83038. }
  83039. /**
  83040. * @param {Vector3} origin the origin of the explosion
  83041. * @param {number} radius the explosion radius
  83042. * @param {number} strength the explosion strength
  83043. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83044. */
  83045. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83046. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83047. if (!this._physicsEngine) {
  83048. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83049. return null;
  83050. }
  83051. var impostors = this._physicsEngine.getImpostors();
  83052. if (impostors.length === 0) {
  83053. return null;
  83054. }
  83055. var event = new PhysicsRadialExplosionEvent(this._scene);
  83056. impostors.forEach(function (impostor) {
  83057. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83058. if (!impostorForceAndContactPoint) {
  83059. return;
  83060. }
  83061. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83062. });
  83063. event.dispose(false);
  83064. return event;
  83065. };
  83066. /**
  83067. * @param {Vector3} origin the origin of the explosion
  83068. * @param {number} radius the explosion radius
  83069. * @param {number} strength the explosion strength
  83070. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83071. */
  83072. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83073. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83074. if (!this._physicsEngine) {
  83075. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83076. return null;
  83077. }
  83078. var impostors = this._physicsEngine.getImpostors();
  83079. if (impostors.length === 0) {
  83080. return null;
  83081. }
  83082. var event = new PhysicsRadialExplosionEvent(this._scene);
  83083. impostors.forEach(function (impostor) {
  83084. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83085. if (!impostorForceAndContactPoint) {
  83086. return;
  83087. }
  83088. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83089. });
  83090. event.dispose(false);
  83091. return event;
  83092. };
  83093. /**
  83094. * @param {Vector3} origin the origin of the explosion
  83095. * @param {number} radius the explosion radius
  83096. * @param {number} strength the explosion strength
  83097. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83098. */
  83099. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83100. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83101. if (!this._physicsEngine) {
  83102. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83103. return null;
  83104. }
  83105. var impostors = this._physicsEngine.getImpostors();
  83106. if (impostors.length === 0) {
  83107. return null;
  83108. }
  83109. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83110. event.dispose(false);
  83111. return event;
  83112. };
  83113. /**
  83114. * @param {Vector3} origin the origin of the updraft
  83115. * @param {number} radius the radius of the updraft
  83116. * @param {number} strength the strength of the updraft
  83117. * @param {number} height the height of the updraft
  83118. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83119. */
  83120. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83121. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83122. if (!this._physicsEngine) {
  83123. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83124. return null;
  83125. }
  83126. if (this._physicsEngine.getImpostors().length === 0) {
  83127. return null;
  83128. }
  83129. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83130. event.dispose(false);
  83131. return event;
  83132. };
  83133. /**
  83134. * @param {Vector3} origin the of the vortex
  83135. * @param {number} radius the radius of the vortex
  83136. * @param {number} strength the strength of the vortex
  83137. * @param {number} height the height of the vortex
  83138. */
  83139. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83140. if (!this._physicsEngine) {
  83141. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83142. return null;
  83143. }
  83144. if (this._physicsEngine.getImpostors().length === 0) {
  83145. return null;
  83146. }
  83147. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83148. event.dispose(false);
  83149. return event;
  83150. };
  83151. return PhysicsHelper;
  83152. }());
  83153. BABYLON.PhysicsHelper = PhysicsHelper;
  83154. /***** Radial explosion *****/
  83155. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83156. function PhysicsRadialExplosionEvent(scene) {
  83157. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83158. this._rays = [];
  83159. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83160. this._scene = scene;
  83161. }
  83162. /**
  83163. * Returns the data related to the radial explosion event (sphere & rays).
  83164. * @returns {PhysicsRadialExplosionEventData}
  83165. */
  83166. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83167. this._dataFetched = true;
  83168. return {
  83169. sphere: this._sphere,
  83170. rays: this._rays,
  83171. };
  83172. };
  83173. /**
  83174. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83175. * @param impostor
  83176. * @param {Vector3} origin the origin of the explosion
  83177. * @param {number} radius the explosion radius
  83178. * @param {number} strength the explosion strength
  83179. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83180. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83181. */
  83182. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83183. if (impostor.mass === 0) {
  83184. return null;
  83185. }
  83186. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83187. return null;
  83188. }
  83189. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83190. return null;
  83191. }
  83192. var impostorObjectCenter = impostor.getObjectCenter();
  83193. var direction = impostorObjectCenter.subtract(origin);
  83194. var ray = new BABYLON.Ray(origin, direction, radius);
  83195. this._rays.push(ray);
  83196. var hit = ray.intersectsMesh(impostor.object);
  83197. var contactPoint = hit.pickedPoint;
  83198. if (!contactPoint) {
  83199. return null;
  83200. }
  83201. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83202. if (distanceFromOrigin > radius) {
  83203. return null;
  83204. }
  83205. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83206. ? strength
  83207. : strength * (1 - (distanceFromOrigin / radius));
  83208. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83209. return { force: force, contactPoint: contactPoint };
  83210. };
  83211. /**
  83212. * Disposes the sphere.
  83213. * @param {bolean} force
  83214. */
  83215. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83216. var _this = this;
  83217. if (force === void 0) { force = true; }
  83218. if (force) {
  83219. this._sphere.dispose();
  83220. }
  83221. else {
  83222. setTimeout(function () {
  83223. if (!_this._dataFetched) {
  83224. _this._sphere.dispose();
  83225. }
  83226. }, 0);
  83227. }
  83228. };
  83229. /*** Helpers ***/
  83230. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83231. if (!this._sphere) {
  83232. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83233. this._sphere.isVisible = false;
  83234. }
  83235. };
  83236. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83237. var impostorObject = impostor.object;
  83238. this._prepareSphere();
  83239. this._sphere.position = origin;
  83240. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83241. this._sphere._updateBoundingInfo();
  83242. this._sphere.computeWorldMatrix(true);
  83243. return this._sphere.intersectsMesh(impostorObject, true);
  83244. };
  83245. return PhysicsRadialExplosionEvent;
  83246. }());
  83247. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83248. /***** Gravitational Field *****/
  83249. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83250. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83251. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83252. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83253. this._physicsHelper = physicsHelper;
  83254. this._scene = scene;
  83255. this._origin = origin;
  83256. this._radius = radius;
  83257. this._strength = strength;
  83258. this._falloff = falloff;
  83259. this._tickCallback = this._tick.bind(this);
  83260. }
  83261. /**
  83262. * Returns the data related to the gravitational field event (sphere).
  83263. * @returns {PhysicsGravitationalFieldEventData}
  83264. */
  83265. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83266. this._dataFetched = true;
  83267. return {
  83268. sphere: this._sphere,
  83269. };
  83270. };
  83271. /**
  83272. * Enables the gravitational field.
  83273. */
  83274. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83275. this._tickCallback.call(this);
  83276. this._scene.registerBeforeRender(this._tickCallback);
  83277. };
  83278. /**
  83279. * Disables the gravitational field.
  83280. */
  83281. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83282. this._scene.unregisterBeforeRender(this._tickCallback);
  83283. };
  83284. /**
  83285. * Disposes the sphere.
  83286. * @param {bolean} force
  83287. */
  83288. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83289. var _this = this;
  83290. if (force === void 0) { force = true; }
  83291. if (force) {
  83292. this._sphere.dispose();
  83293. }
  83294. else {
  83295. setTimeout(function () {
  83296. if (!_this._dataFetched) {
  83297. _this._sphere.dispose();
  83298. }
  83299. }, 0);
  83300. }
  83301. };
  83302. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83303. // Since the params won't change, we fetch the event only once
  83304. if (this._sphere) {
  83305. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83306. }
  83307. else {
  83308. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83309. if (radialExplosionEvent) {
  83310. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83311. }
  83312. }
  83313. };
  83314. return PhysicsGravitationalFieldEvent;
  83315. }());
  83316. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83317. /***** Updraft *****/
  83318. var PhysicsUpdraftEvent = /** @class */ (function () {
  83319. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83320. this._scene = _scene;
  83321. this._origin = _origin;
  83322. this._radius = _radius;
  83323. this._strength = _strength;
  83324. this._height = _height;
  83325. this._updraftMode = _updraftMode;
  83326. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83327. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83328. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83329. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83330. this._physicsEngine = this._scene.getPhysicsEngine();
  83331. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83332. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83333. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83334. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83335. }
  83336. this._tickCallback = this._tick.bind(this);
  83337. }
  83338. /**
  83339. * Returns the data related to the updraft event (cylinder).
  83340. * @returns {PhysicsUpdraftEventData}
  83341. */
  83342. PhysicsUpdraftEvent.prototype.getData = function () {
  83343. this._dataFetched = true;
  83344. return {
  83345. cylinder: this._cylinder,
  83346. };
  83347. };
  83348. /**
  83349. * Enables the updraft.
  83350. */
  83351. PhysicsUpdraftEvent.prototype.enable = function () {
  83352. this._tickCallback.call(this);
  83353. this._scene.registerBeforeRender(this._tickCallback);
  83354. };
  83355. /**
  83356. * Disables the cortex.
  83357. */
  83358. PhysicsUpdraftEvent.prototype.disable = function () {
  83359. this._scene.unregisterBeforeRender(this._tickCallback);
  83360. };
  83361. /**
  83362. * Disposes the sphere.
  83363. * @param {bolean} force
  83364. */
  83365. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83366. var _this = this;
  83367. if (force === void 0) { force = true; }
  83368. if (force) {
  83369. this._cylinder.dispose();
  83370. }
  83371. else {
  83372. setTimeout(function () {
  83373. if (!_this._dataFetched) {
  83374. _this._cylinder.dispose();
  83375. }
  83376. }, 0);
  83377. }
  83378. };
  83379. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83380. if (impostor.mass === 0) {
  83381. return null;
  83382. }
  83383. if (!this._intersectsWithCylinder(impostor)) {
  83384. return null;
  83385. }
  83386. var impostorObjectCenter = impostor.getObjectCenter();
  83387. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83388. var direction = this._originDirection;
  83389. }
  83390. else {
  83391. var direction = impostorObjectCenter.subtract(this._originTop);
  83392. }
  83393. var multiplier = this._strength * -1;
  83394. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83395. return { force: force, contactPoint: impostorObjectCenter };
  83396. };
  83397. PhysicsUpdraftEvent.prototype._tick = function () {
  83398. var _this = this;
  83399. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83400. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83401. if (!impostorForceAndContactPoint) {
  83402. return;
  83403. }
  83404. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83405. });
  83406. };
  83407. /*** Helpers ***/
  83408. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83409. if (!this._cylinder) {
  83410. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83411. height: this._height,
  83412. diameter: this._radius * 2,
  83413. }, this._scene);
  83414. this._cylinder.isVisible = false;
  83415. }
  83416. };
  83417. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83418. var impostorObject = impostor.object;
  83419. this._prepareCylinder();
  83420. this._cylinder.position = this._cylinderPosition;
  83421. return this._cylinder.intersectsMesh(impostorObject, true);
  83422. };
  83423. return PhysicsUpdraftEvent;
  83424. }());
  83425. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83426. /***** Vortex *****/
  83427. var PhysicsVortexEvent = /** @class */ (function () {
  83428. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83429. this._scene = _scene;
  83430. this._origin = _origin;
  83431. this._radius = _radius;
  83432. this._strength = _strength;
  83433. this._height = _height;
  83434. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83435. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83436. this._updraftMultiplier = 0.02;
  83437. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83438. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83439. this._physicsEngine = this._scene.getPhysicsEngine();
  83440. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83441. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83442. this._tickCallback = this._tick.bind(this);
  83443. }
  83444. /**
  83445. * Returns the data related to the vortex event (cylinder).
  83446. * @returns {PhysicsVortexEventData}
  83447. */
  83448. PhysicsVortexEvent.prototype.getData = function () {
  83449. this._dataFetched = true;
  83450. return {
  83451. cylinder: this._cylinder,
  83452. };
  83453. };
  83454. /**
  83455. * Enables the vortex.
  83456. */
  83457. PhysicsVortexEvent.prototype.enable = function () {
  83458. this._tickCallback.call(this);
  83459. this._scene.registerBeforeRender(this._tickCallback);
  83460. };
  83461. /**
  83462. * Disables the cortex.
  83463. */
  83464. PhysicsVortexEvent.prototype.disable = function () {
  83465. this._scene.unregisterBeforeRender(this._tickCallback);
  83466. };
  83467. /**
  83468. * Disposes the sphere.
  83469. * @param {bolean} force
  83470. */
  83471. PhysicsVortexEvent.prototype.dispose = function (force) {
  83472. var _this = this;
  83473. if (force === void 0) { force = true; }
  83474. if (force) {
  83475. this._cylinder.dispose();
  83476. }
  83477. else {
  83478. setTimeout(function () {
  83479. if (!_this._dataFetched) {
  83480. _this._cylinder.dispose();
  83481. }
  83482. }, 0);
  83483. }
  83484. };
  83485. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83486. if (impostor.mass === 0) {
  83487. return null;
  83488. }
  83489. if (!this._intersectsWithCylinder(impostor)) {
  83490. return null;
  83491. }
  83492. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83493. return null;
  83494. }
  83495. var impostorObjectCenter = impostor.getObjectCenter();
  83496. 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)
  83497. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83498. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83499. var hit = ray.intersectsMesh(impostor.object);
  83500. var contactPoint = hit.pickedPoint;
  83501. if (!contactPoint) {
  83502. return null;
  83503. }
  83504. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83505. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83506. var directionToOrigin = contactPoint.normalize();
  83507. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83508. directionToOrigin = directionToOrigin.negate();
  83509. }
  83510. // TODO: find a more physically based solution
  83511. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83512. var forceX = directionToOrigin.x * this._strength / 8;
  83513. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83514. var forceZ = directionToOrigin.z * this._strength / 8;
  83515. }
  83516. else {
  83517. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83518. var forceY = this._originTop.y * this._updraftMultiplier;
  83519. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83520. }
  83521. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83522. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83523. return { force: force, contactPoint: impostorObjectCenter };
  83524. };
  83525. PhysicsVortexEvent.prototype._tick = function () {
  83526. var _this = this;
  83527. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83528. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83529. if (!impostorForceAndContactPoint) {
  83530. return;
  83531. }
  83532. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83533. });
  83534. };
  83535. /*** Helpers ***/
  83536. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83537. if (!this._cylinder) {
  83538. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83539. height: this._height,
  83540. diameter: this._radius * 2,
  83541. }, this._scene);
  83542. this._cylinder.isVisible = false;
  83543. }
  83544. };
  83545. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83546. var impostorObject = impostor.object;
  83547. this._prepareCylinder();
  83548. this._cylinder.position = this._cylinderPosition;
  83549. return this._cylinder.intersectsMesh(impostorObject, true);
  83550. };
  83551. return PhysicsVortexEvent;
  83552. }());
  83553. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83554. /***** Enums *****/
  83555. /**
  83556. * The strenght of the force in correspondence to the distance of the affected object
  83557. */
  83558. var PhysicsRadialImpulseFalloff;
  83559. (function (PhysicsRadialImpulseFalloff) {
  83560. /** Defines that impulse is constant in strength across it's whole radius */
  83561. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83562. /** DEfines that impulse gets weaker if it's further from the origin */
  83563. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83564. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83565. /**
  83566. * The strenght of the force in correspondence to the distance of the affected object
  83567. */
  83568. var PhysicsUpdraftMode;
  83569. (function (PhysicsUpdraftMode) {
  83570. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83571. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83572. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83573. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83574. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83575. })(BABYLON || (BABYLON = {}));
  83576. //# sourceMappingURL=babylon.physicsHelper.js.map
  83577. var BABYLON;
  83578. (function (BABYLON) {
  83579. var CannonJSPlugin = /** @class */ (function () {
  83580. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83581. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83582. if (iterations === void 0) { iterations = 10; }
  83583. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83584. this.name = "CannonJSPlugin";
  83585. this._physicsMaterials = new Array();
  83586. this._fixedTimeStep = 1 / 60;
  83587. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83588. this.BJSCANNON = CANNON;
  83589. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83590. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83591. this._tmpPosition = BABYLON.Vector3.Zero();
  83592. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83593. this._tmpUnityRotation = new BABYLON.Quaternion();
  83594. if (!this.isSupported()) {
  83595. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83596. return;
  83597. }
  83598. this._extendNamespace();
  83599. this.world = new this.BJSCANNON.World();
  83600. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83601. this.world.solver.iterations = iterations;
  83602. }
  83603. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83604. this.world.gravity.copy(gravity);
  83605. };
  83606. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83607. this._fixedTimeStep = timeStep;
  83608. };
  83609. CannonJSPlugin.prototype.getTimeStep = function () {
  83610. return this._fixedTimeStep;
  83611. };
  83612. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83613. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83614. };
  83615. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83616. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83617. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83618. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83619. };
  83620. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83621. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83622. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83623. impostor.physicsBody.applyForce(impulse, worldPoint);
  83624. };
  83625. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83626. //parent-child relationship. Does this impostor has a parent impostor?
  83627. if (impostor.parent) {
  83628. if (impostor.physicsBody) {
  83629. this.removePhysicsBody(impostor);
  83630. //TODO is that needed?
  83631. impostor.forceUpdate();
  83632. }
  83633. return;
  83634. }
  83635. //should a new body be created for this impostor?
  83636. if (impostor.isBodyInitRequired()) {
  83637. var shape = this._createShape(impostor);
  83638. //unregister events, if body is being changed
  83639. var oldBody = impostor.physicsBody;
  83640. if (oldBody) {
  83641. this.removePhysicsBody(impostor);
  83642. }
  83643. //create the body and material
  83644. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83645. var bodyCreationObject = {
  83646. mass: impostor.getParam("mass"),
  83647. material: material
  83648. };
  83649. // A simple extend, in case native options were used.
  83650. var nativeOptions = impostor.getParam("nativeOptions");
  83651. for (var key in nativeOptions) {
  83652. if (nativeOptions.hasOwnProperty(key)) {
  83653. bodyCreationObject[key] = nativeOptions[key];
  83654. }
  83655. }
  83656. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83657. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83658. this.world.addEventListener("preStep", impostor.beforeStep);
  83659. this.world.addEventListener("postStep", impostor.afterStep);
  83660. impostor.physicsBody.addShape(shape);
  83661. this.world.add(impostor.physicsBody);
  83662. //try to keep the body moving in the right direction by taking old properties.
  83663. //Should be tested!
  83664. if (oldBody) {
  83665. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83666. impostor.physicsBody[param].copy(oldBody[param]);
  83667. });
  83668. }
  83669. this._processChildMeshes(impostor);
  83670. }
  83671. //now update the body's transformation
  83672. this._updatePhysicsBodyTransformation(impostor);
  83673. };
  83674. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83675. var _this = this;
  83676. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83677. var currentRotation = mainImpostor.object.rotationQuaternion;
  83678. if (meshChildren.length) {
  83679. var processMesh = function (localPosition, mesh) {
  83680. if (!currentRotation || !mesh.rotationQuaternion) {
  83681. return;
  83682. }
  83683. var childImpostor = mesh.getPhysicsImpostor();
  83684. if (childImpostor) {
  83685. var parent = childImpostor.parent;
  83686. if (parent !== mainImpostor) {
  83687. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83688. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83689. if (childImpostor.physicsBody) {
  83690. _this.removePhysicsBody(childImpostor);
  83691. childImpostor.physicsBody = null;
  83692. }
  83693. childImpostor.parent = mainImpostor;
  83694. childImpostor.resetUpdateFlags();
  83695. 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));
  83696. //Add the mass of the children.
  83697. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83698. }
  83699. }
  83700. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83701. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83702. };
  83703. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83704. }
  83705. };
  83706. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83707. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83708. this.world.removeEventListener("preStep", impostor.beforeStep);
  83709. this.world.removeEventListener("postStep", impostor.afterStep);
  83710. this.world.remove(impostor.physicsBody);
  83711. };
  83712. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83713. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83714. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83715. if (!mainBody || !connectedBody) {
  83716. return;
  83717. }
  83718. var constraint;
  83719. var jointData = impostorJoint.joint.jointData;
  83720. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83721. var constraintData = {
  83722. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83723. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83724. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83725. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83726. maxForce: jointData.nativeParams.maxForce,
  83727. collideConnected: !!jointData.collision
  83728. };
  83729. switch (impostorJoint.joint.type) {
  83730. case BABYLON.PhysicsJoint.HingeJoint:
  83731. case BABYLON.PhysicsJoint.Hinge2Joint:
  83732. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83733. break;
  83734. case BABYLON.PhysicsJoint.DistanceJoint:
  83735. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83736. break;
  83737. case BABYLON.PhysicsJoint.SpringJoint:
  83738. var springData = jointData;
  83739. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83740. restLength: springData.length,
  83741. stiffness: springData.stiffness,
  83742. damping: springData.damping,
  83743. localAnchorA: constraintData.pivotA,
  83744. localAnchorB: constraintData.pivotB
  83745. });
  83746. break;
  83747. case BABYLON.PhysicsJoint.LockJoint:
  83748. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83749. break;
  83750. case BABYLON.PhysicsJoint.PointToPointJoint:
  83751. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83752. default:
  83753. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83754. break;
  83755. }
  83756. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83757. constraint.collideConnected = !!jointData.collision;
  83758. impostorJoint.joint.physicsJoint = constraint;
  83759. //don't add spring as constraint, as it is not one.
  83760. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83761. this.world.addConstraint(constraint);
  83762. }
  83763. else {
  83764. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83765. constraint.applyForce();
  83766. });
  83767. }
  83768. };
  83769. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83770. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83771. };
  83772. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83773. var index;
  83774. var mat;
  83775. for (index = 0; index < this._physicsMaterials.length; index++) {
  83776. mat = this._physicsMaterials[index];
  83777. if (mat.friction === friction && mat.restitution === restitution) {
  83778. return mat;
  83779. }
  83780. }
  83781. var currentMat = new this.BJSCANNON.Material(name);
  83782. currentMat.friction = friction;
  83783. currentMat.restitution = restitution;
  83784. this._physicsMaterials.push(currentMat);
  83785. return currentMat;
  83786. };
  83787. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83788. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83789. };
  83790. CannonJSPlugin.prototype._createShape = function (impostor) {
  83791. var object = impostor.object;
  83792. var returnValue;
  83793. var extendSize = impostor.getObjectExtendSize();
  83794. switch (impostor.type) {
  83795. case BABYLON.PhysicsImpostor.SphereImpostor:
  83796. var radiusX = extendSize.x;
  83797. var radiusY = extendSize.y;
  83798. var radiusZ = extendSize.z;
  83799. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83800. break;
  83801. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83802. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83803. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83804. break;
  83805. case BABYLON.PhysicsImpostor.BoxImpostor:
  83806. var box = extendSize.scale(0.5);
  83807. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83808. break;
  83809. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83810. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83811. returnValue = new this.BJSCANNON.Plane();
  83812. break;
  83813. case BABYLON.PhysicsImpostor.MeshImpostor:
  83814. // should transform the vertex data to world coordinates!!
  83815. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83816. var rawFaces = object.getIndices ? object.getIndices() : [];
  83817. if (!rawVerts)
  83818. return;
  83819. // get only scale! so the object could transform correctly.
  83820. var oldPosition = object.position.clone();
  83821. var oldRotation = object.rotation && object.rotation.clone();
  83822. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83823. object.position.copyFromFloats(0, 0, 0);
  83824. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83825. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83826. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83827. var transform = object.computeWorldMatrix(true);
  83828. // convert rawVerts to object space
  83829. var temp = new Array();
  83830. var index;
  83831. for (index = 0; index < rawVerts.length; index += 3) {
  83832. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83833. }
  83834. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83835. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83836. //now set back the transformation!
  83837. object.position.copyFrom(oldPosition);
  83838. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83839. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83840. break;
  83841. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83842. var oldPosition2 = object.position.clone();
  83843. var oldRotation2 = object.rotation && object.rotation.clone();
  83844. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83845. object.position.copyFromFloats(0, 0, 0);
  83846. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83847. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83848. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83849. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83850. returnValue = this._createHeightmap(object);
  83851. object.position.copyFrom(oldPosition2);
  83852. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83853. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83854. object.computeWorldMatrix(true);
  83855. break;
  83856. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83857. returnValue = new this.BJSCANNON.Particle();
  83858. break;
  83859. }
  83860. return returnValue;
  83861. };
  83862. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83863. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83864. var transform = object.computeWorldMatrix(true);
  83865. // convert rawVerts to object space
  83866. var temp = new Array();
  83867. var index;
  83868. for (index = 0; index < pos.length; index += 3) {
  83869. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83870. }
  83871. pos = temp;
  83872. var matrix = new Array();
  83873. //For now pointDepth will not be used and will be automatically calculated.
  83874. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83875. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83876. var boundingInfo = object.getBoundingInfo();
  83877. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83878. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83879. var elementSize = dim * 2 / arraySize;
  83880. for (var i = 0; i < pos.length; i = i + 3) {
  83881. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83882. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83883. var y = -pos[i + 2] + minY;
  83884. if (!matrix[x]) {
  83885. matrix[x] = [];
  83886. }
  83887. if (!matrix[x][z]) {
  83888. matrix[x][z] = y;
  83889. }
  83890. matrix[x][z] = Math.max(y, matrix[x][z]);
  83891. }
  83892. for (var x = 0; x <= arraySize; ++x) {
  83893. if (!matrix[x]) {
  83894. var loc = 1;
  83895. while (!matrix[(x + loc) % arraySize]) {
  83896. loc++;
  83897. }
  83898. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83899. //console.log("missing x", x);
  83900. }
  83901. for (var z = 0; z <= arraySize; ++z) {
  83902. if (!matrix[x][z]) {
  83903. var loc = 1;
  83904. var newValue;
  83905. while (newValue === undefined) {
  83906. newValue = matrix[x][(z + loc++) % arraySize];
  83907. }
  83908. matrix[x][z] = newValue;
  83909. }
  83910. }
  83911. }
  83912. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83913. elementSize: elementSize
  83914. });
  83915. //For future reference, needed for body transformation
  83916. shape.minY = minY;
  83917. return shape;
  83918. };
  83919. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83920. var object = impostor.object;
  83921. //make sure it is updated...
  83922. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83923. // The delta between the mesh position and the mesh bounding box center
  83924. var bInfo = object.getBoundingInfo();
  83925. if (!bInfo)
  83926. return;
  83927. var center = impostor.getObjectCenter();
  83928. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83929. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83930. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83931. this._tmpPosition.copyFrom(center);
  83932. var quaternion = object.rotationQuaternion;
  83933. if (!quaternion) {
  83934. return;
  83935. }
  83936. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83937. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83938. //-90 DEG in X, precalculated
  83939. quaternion = quaternion.multiply(this._minus90X);
  83940. //Invert! (Precalculated, 90 deg in X)
  83941. //No need to clone. this will never change.
  83942. impostor.setDeltaRotation(this._plus90X);
  83943. }
  83944. //If it is a heightfield, if should be centered.
  83945. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83946. var mesh = object;
  83947. var boundingInfo = mesh.getBoundingInfo();
  83948. //calculate the correct body position:
  83949. var rotationQuaternion = mesh.rotationQuaternion;
  83950. mesh.rotationQuaternion = this._tmpUnityRotation;
  83951. mesh.computeWorldMatrix(true);
  83952. //get original center with no rotation
  83953. var c = center.clone();
  83954. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83955. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83956. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83957. mesh.setPreTransformMatrix(p);
  83958. mesh.computeWorldMatrix(true);
  83959. //calculate the translation
  83960. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83961. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83962. //add it inverted to the delta
  83963. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83964. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83965. //rotation is back
  83966. mesh.rotationQuaternion = rotationQuaternion;
  83967. mesh.setPreTransformMatrix(oldPivot);
  83968. mesh.computeWorldMatrix(true);
  83969. }
  83970. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83971. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83972. //this._tmpPosition.copyFrom(object.position);
  83973. }
  83974. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83975. //Now update the impostor object
  83976. impostor.physicsBody.position.copy(this._tmpPosition);
  83977. impostor.physicsBody.quaternion.copy(quaternion);
  83978. };
  83979. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83980. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83981. if (impostor.object.rotationQuaternion) {
  83982. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83983. }
  83984. };
  83985. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83986. impostor.physicsBody.position.copy(newPosition);
  83987. impostor.physicsBody.quaternion.copy(newRotation);
  83988. };
  83989. CannonJSPlugin.prototype.isSupported = function () {
  83990. return this.BJSCANNON !== undefined;
  83991. };
  83992. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83993. impostor.physicsBody.velocity.copy(velocity);
  83994. };
  83995. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83996. impostor.physicsBody.angularVelocity.copy(velocity);
  83997. };
  83998. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83999. var v = impostor.physicsBody.velocity;
  84000. if (!v) {
  84001. return null;
  84002. }
  84003. return new BABYLON.Vector3(v.x, v.y, v.z);
  84004. };
  84005. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84006. var v = impostor.physicsBody.angularVelocity;
  84007. if (!v) {
  84008. return null;
  84009. }
  84010. return new BABYLON.Vector3(v.x, v.y, v.z);
  84011. };
  84012. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84013. impostor.physicsBody.mass = mass;
  84014. impostor.physicsBody.updateMassProperties();
  84015. };
  84016. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84017. return impostor.physicsBody.mass;
  84018. };
  84019. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84020. return impostor.physicsBody.material.friction;
  84021. };
  84022. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84023. impostor.physicsBody.material.friction = friction;
  84024. };
  84025. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84026. return impostor.physicsBody.material.restitution;
  84027. };
  84028. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84029. impostor.physicsBody.material.restitution = restitution;
  84030. };
  84031. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84032. impostor.physicsBody.sleep();
  84033. };
  84034. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84035. impostor.physicsBody.wakeUp();
  84036. };
  84037. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84038. joint.physicsJoint.distance = maxDistance;
  84039. };
  84040. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84041. // if (!motorIndex) {
  84042. // joint.physicsJoint.enableMotor();
  84043. // }
  84044. // }
  84045. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84046. // if (!motorIndex) {
  84047. // joint.physicsJoint.disableMotor();
  84048. // }
  84049. // }
  84050. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84051. if (!motorIndex) {
  84052. joint.physicsJoint.enableMotor();
  84053. joint.physicsJoint.setMotorSpeed(speed);
  84054. if (maxForce) {
  84055. this.setLimit(joint, maxForce);
  84056. }
  84057. }
  84058. };
  84059. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84060. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84061. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84062. };
  84063. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84064. var body = impostor.physicsBody;
  84065. mesh.position.x = body.position.x;
  84066. mesh.position.y = body.position.y;
  84067. mesh.position.z = body.position.z;
  84068. if (mesh.rotationQuaternion) {
  84069. mesh.rotationQuaternion.x = body.quaternion.x;
  84070. mesh.rotationQuaternion.y = body.quaternion.y;
  84071. mesh.rotationQuaternion.z = body.quaternion.z;
  84072. mesh.rotationQuaternion.w = body.quaternion.w;
  84073. }
  84074. };
  84075. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84076. var shape = impostor.physicsBody.shapes[0];
  84077. return shape.boundingSphereRadius;
  84078. };
  84079. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84080. var shape = impostor.physicsBody.shapes[0];
  84081. result.x = shape.halfExtents.x * 2;
  84082. result.y = shape.halfExtents.y * 2;
  84083. result.z = shape.halfExtents.z * 2;
  84084. };
  84085. CannonJSPlugin.prototype.dispose = function () {
  84086. };
  84087. CannonJSPlugin.prototype._extendNamespace = function () {
  84088. //this will force cannon to execute at least one step when using interpolation
  84089. var step_tmp1 = new this.BJSCANNON.Vec3();
  84090. var Engine = this.BJSCANNON;
  84091. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84092. maxSubSteps = maxSubSteps || 10;
  84093. timeSinceLastCalled = timeSinceLastCalled || 0;
  84094. if (timeSinceLastCalled === 0) {
  84095. this.internalStep(dt);
  84096. this.time += dt;
  84097. }
  84098. else {
  84099. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84100. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84101. var t0 = performance.now();
  84102. for (var i = 0; i !== internalSteps; i++) {
  84103. this.internalStep(dt);
  84104. if (performance.now() - t0 > dt * 1000) {
  84105. break;
  84106. }
  84107. }
  84108. this.time += timeSinceLastCalled;
  84109. var h = this.time % dt;
  84110. var h_div_dt = h / dt;
  84111. var interpvelo = step_tmp1;
  84112. var bodies = this.bodies;
  84113. for (var j = 0; j !== bodies.length; j++) {
  84114. var b = bodies[j];
  84115. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84116. b.position.vsub(b.previousPosition, interpvelo);
  84117. interpvelo.scale(h_div_dt, interpvelo);
  84118. b.position.vadd(interpvelo, b.interpolatedPosition);
  84119. }
  84120. else {
  84121. b.interpolatedPosition.copy(b.position);
  84122. b.interpolatedQuaternion.copy(b.quaternion);
  84123. }
  84124. }
  84125. }
  84126. };
  84127. };
  84128. return CannonJSPlugin;
  84129. }());
  84130. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84131. })(BABYLON || (BABYLON = {}));
  84132. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84133. var BABYLON;
  84134. (function (BABYLON) {
  84135. var OimoJSPlugin = /** @class */ (function () {
  84136. function OimoJSPlugin(iterations) {
  84137. this.name = "OimoJSPlugin";
  84138. this._tmpImpostorsArray = [];
  84139. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84140. this.BJSOIMO = OIMO;
  84141. this.world = new this.BJSOIMO.World({
  84142. iterations: iterations
  84143. });
  84144. this.world.clear();
  84145. }
  84146. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84147. this.world.gravity.copy(gravity);
  84148. };
  84149. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84150. this.world.timeStep = timeStep;
  84151. };
  84152. OimoJSPlugin.prototype.getTimeStep = function () {
  84153. return this.world.timeStep;
  84154. };
  84155. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84156. var _this = this;
  84157. impostors.forEach(function (impostor) {
  84158. impostor.beforeStep();
  84159. });
  84160. this.world.step();
  84161. impostors.forEach(function (impostor) {
  84162. impostor.afterStep();
  84163. //update the ordered impostors array
  84164. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84165. });
  84166. //check for collisions
  84167. var contact = this.world.contacts;
  84168. while (contact !== null) {
  84169. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84170. contact = contact.next;
  84171. continue;
  84172. }
  84173. //is this body colliding with any other? get the impostor
  84174. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84175. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84176. if (!mainImpostor || !collidingImpostor) {
  84177. contact = contact.next;
  84178. continue;
  84179. }
  84180. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84181. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84182. contact = contact.next;
  84183. }
  84184. };
  84185. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84186. var mass = impostor.physicsBody.mass;
  84187. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84188. };
  84189. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84190. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84191. this.applyImpulse(impostor, force, contactPoint);
  84192. };
  84193. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84194. var _this = this;
  84195. //parent-child relationship. Does this impostor has a parent impostor?
  84196. if (impostor.parent) {
  84197. if (impostor.physicsBody) {
  84198. this.removePhysicsBody(impostor);
  84199. //TODO is that needed?
  84200. impostor.forceUpdate();
  84201. }
  84202. return;
  84203. }
  84204. if (impostor.isBodyInitRequired()) {
  84205. var bodyConfig = {
  84206. name: impostor.uniqueId,
  84207. //Oimo must have mass, also for static objects.
  84208. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84209. size: [],
  84210. type: [],
  84211. pos: [],
  84212. posShape: [],
  84213. rot: [],
  84214. rotShape: [],
  84215. move: impostor.getParam("mass") !== 0,
  84216. density: impostor.getParam("mass"),
  84217. friction: impostor.getParam("friction"),
  84218. restitution: impostor.getParam("restitution"),
  84219. //Supporting older versions of Oimo
  84220. world: this.world
  84221. };
  84222. var impostors = [impostor];
  84223. var addToArray = function (parent) {
  84224. if (!parent.getChildMeshes)
  84225. return;
  84226. parent.getChildMeshes().forEach(function (m) {
  84227. if (m.physicsImpostor) {
  84228. impostors.push(m.physicsImpostor);
  84229. //m.physicsImpostor._init();
  84230. }
  84231. });
  84232. };
  84233. addToArray(impostor.object);
  84234. var checkWithEpsilon_1 = function (value) {
  84235. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84236. };
  84237. impostors.forEach(function (i) {
  84238. if (!i.object.rotationQuaternion) {
  84239. return;
  84240. }
  84241. //get the correct bounding box
  84242. var oldQuaternion = i.object.rotationQuaternion;
  84243. var rot = oldQuaternion.toEulerAngles();
  84244. var extendSize = i.getObjectExtendSize();
  84245. var radToDeg = 57.295779513082320876;
  84246. if (i === impostor) {
  84247. var center = impostor.getObjectCenter();
  84248. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84249. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84250. //Can also use Array.prototype.push.apply
  84251. bodyConfig.pos.push(center.x);
  84252. bodyConfig.pos.push(center.y);
  84253. bodyConfig.pos.push(center.z);
  84254. bodyConfig.posShape.push(0, 0, 0);
  84255. //tmp solution
  84256. bodyConfig.rot.push(rot.x * radToDeg);
  84257. bodyConfig.rot.push(rot.y * radToDeg);
  84258. bodyConfig.rot.push(rot.z * radToDeg);
  84259. bodyConfig.rotShape.push(0, 0, 0);
  84260. }
  84261. else {
  84262. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84263. bodyConfig.posShape.push(localPosition.x);
  84264. bodyConfig.posShape.push(localPosition.y);
  84265. bodyConfig.posShape.push(localPosition.z);
  84266. bodyConfig.pos.push(0, 0, 0);
  84267. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84268. bodyConfig.rot.push(0);
  84269. bodyConfig.rot.push(0);
  84270. bodyConfig.rot.push(0);
  84271. bodyConfig.rotShape.push(rot.x * radToDeg);
  84272. bodyConfig.rotShape.push(rot.y * radToDeg);
  84273. bodyConfig.rotShape.push(rot.z * radToDeg);
  84274. }
  84275. // register mesh
  84276. switch (i.type) {
  84277. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84278. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84279. case BABYLON.PhysicsImpostor.SphereImpostor:
  84280. var radiusX = extendSize.x;
  84281. var radiusY = extendSize.y;
  84282. var radiusZ = extendSize.z;
  84283. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84284. bodyConfig.type.push('sphere');
  84285. //due to the way oimo works with compounds, add 3 times
  84286. bodyConfig.size.push(size);
  84287. bodyConfig.size.push(size);
  84288. bodyConfig.size.push(size);
  84289. break;
  84290. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84291. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84292. var sizeY = checkWithEpsilon_1(extendSize.y);
  84293. bodyConfig.type.push('cylinder');
  84294. bodyConfig.size.push(sizeX);
  84295. bodyConfig.size.push(sizeY);
  84296. //due to the way oimo works with compounds, add one more value.
  84297. bodyConfig.size.push(sizeY);
  84298. break;
  84299. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84300. case BABYLON.PhysicsImpostor.BoxImpostor:
  84301. default:
  84302. var sizeX = checkWithEpsilon_1(extendSize.x);
  84303. var sizeY = checkWithEpsilon_1(extendSize.y);
  84304. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84305. bodyConfig.type.push('box');
  84306. //if (i === impostor) {
  84307. bodyConfig.size.push(sizeX);
  84308. bodyConfig.size.push(sizeY);
  84309. bodyConfig.size.push(sizeZ);
  84310. //} else {
  84311. // bodyConfig.size.push(0,0,0);
  84312. //}
  84313. break;
  84314. }
  84315. //actually not needed, but hey...
  84316. i.object.rotationQuaternion = oldQuaternion;
  84317. });
  84318. impostor.physicsBody = this.world.add(bodyConfig);
  84319. }
  84320. else {
  84321. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84322. }
  84323. impostor.setDeltaPosition(this._tmpPositionVector);
  84324. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84325. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84326. };
  84327. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84328. //impostor.physicsBody.dispose();
  84329. //Same as : (older oimo versions)
  84330. this.world.removeRigidBody(impostor.physicsBody);
  84331. };
  84332. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84333. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84334. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84335. if (!mainBody || !connectedBody) {
  84336. return;
  84337. }
  84338. var jointData = impostorJoint.joint.jointData;
  84339. var options = jointData.nativeParams || {};
  84340. var type;
  84341. var nativeJointData = {
  84342. body1: mainBody,
  84343. body2: connectedBody,
  84344. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84345. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84346. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84347. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84348. min: options.min,
  84349. max: options.max,
  84350. collision: options.collision || jointData.collision,
  84351. spring: options.spring,
  84352. //supporting older version of Oimo
  84353. world: this.world
  84354. };
  84355. switch (impostorJoint.joint.type) {
  84356. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84357. type = "jointBall";
  84358. break;
  84359. case BABYLON.PhysicsJoint.SpringJoint:
  84360. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84361. var springData = jointData;
  84362. nativeJointData.min = springData.length || nativeJointData.min;
  84363. //Max should also be set, just make sure it is at least min
  84364. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84365. case BABYLON.PhysicsJoint.DistanceJoint:
  84366. type = "jointDistance";
  84367. nativeJointData.max = jointData.maxDistance;
  84368. break;
  84369. case BABYLON.PhysicsJoint.PrismaticJoint:
  84370. type = "jointPrisme";
  84371. break;
  84372. case BABYLON.PhysicsJoint.SliderJoint:
  84373. type = "jointSlide";
  84374. break;
  84375. case BABYLON.PhysicsJoint.WheelJoint:
  84376. type = "jointWheel";
  84377. break;
  84378. case BABYLON.PhysicsJoint.HingeJoint:
  84379. default:
  84380. type = "jointHinge";
  84381. break;
  84382. }
  84383. nativeJointData.type = type;
  84384. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84385. };
  84386. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84387. //Bug in Oimo prevents us from disposing a joint in the playground
  84388. //joint.joint.physicsJoint.dispose();
  84389. //So we will bruteforce it!
  84390. try {
  84391. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84392. }
  84393. catch (e) {
  84394. BABYLON.Tools.Warn(e);
  84395. }
  84396. };
  84397. OimoJSPlugin.prototype.isSupported = function () {
  84398. return this.BJSOIMO !== undefined;
  84399. };
  84400. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84401. if (!impostor.physicsBody.sleeping) {
  84402. //TODO check that
  84403. /*if (impostor.physicsBody.shapes.next) {
  84404. var parentShape = this._getLastShape(impostor.physicsBody);
  84405. impostor.object.position.copyFrom(parentShape.position);
  84406. console.log(parentShape.position);
  84407. } else {*/
  84408. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84409. //}
  84410. if (impostor.object.rotationQuaternion) {
  84411. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84412. }
  84413. }
  84414. };
  84415. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84416. var body = impostor.physicsBody;
  84417. body.position.copy(newPosition);
  84418. body.orientation.copy(newRotation);
  84419. body.syncShapes();
  84420. body.awake();
  84421. };
  84422. /*private _getLastShape(body: any): any {
  84423. var lastShape = body.shapes;
  84424. while (lastShape.next) {
  84425. lastShape = lastShape.next;
  84426. }
  84427. return lastShape;
  84428. }*/
  84429. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84430. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84431. };
  84432. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84433. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84434. };
  84435. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84436. var v = impostor.physicsBody.linearVelocity;
  84437. if (!v) {
  84438. return null;
  84439. }
  84440. return new BABYLON.Vector3(v.x, v.y, v.z);
  84441. };
  84442. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84443. var v = impostor.physicsBody.angularVelocity;
  84444. if (!v) {
  84445. return null;
  84446. }
  84447. return new BABYLON.Vector3(v.x, v.y, v.z);
  84448. };
  84449. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84450. var staticBody = mass === 0;
  84451. //this will actually set the body's density and not its mass.
  84452. //But this is how oimo treats the mass variable.
  84453. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84454. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84455. };
  84456. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84457. return impostor.physicsBody.shapes.density;
  84458. };
  84459. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84460. return impostor.physicsBody.shapes.friction;
  84461. };
  84462. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84463. impostor.physicsBody.shapes.friction = friction;
  84464. };
  84465. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84466. return impostor.physicsBody.shapes.restitution;
  84467. };
  84468. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84469. impostor.physicsBody.shapes.restitution = restitution;
  84470. };
  84471. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84472. impostor.physicsBody.sleep();
  84473. };
  84474. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84475. impostor.physicsBody.awake();
  84476. };
  84477. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84478. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84479. if (minDistance !== void 0) {
  84480. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84481. }
  84482. };
  84483. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84484. //TODO separate rotational and transational motors.
  84485. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84486. if (motor) {
  84487. motor.setMotor(speed, maxForce);
  84488. }
  84489. };
  84490. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84491. //TODO separate rotational and transational motors.
  84492. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84493. if (motor) {
  84494. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84495. }
  84496. };
  84497. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84498. var body = impostor.physicsBody;
  84499. mesh.position.x = body.position.x;
  84500. mesh.position.y = body.position.y;
  84501. mesh.position.z = body.position.z;
  84502. if (mesh.rotationQuaternion) {
  84503. mesh.rotationQuaternion.x = body.orientation.x;
  84504. mesh.rotationQuaternion.y = body.orientation.y;
  84505. mesh.rotationQuaternion.z = body.orientation.z;
  84506. mesh.rotationQuaternion.w = body.orientation.s;
  84507. }
  84508. };
  84509. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84510. return impostor.physicsBody.shapes.radius;
  84511. };
  84512. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84513. var shape = impostor.physicsBody.shapes;
  84514. result.x = shape.halfWidth * 2;
  84515. result.y = shape.halfHeight * 2;
  84516. result.z = shape.halfDepth * 2;
  84517. };
  84518. OimoJSPlugin.prototype.dispose = function () {
  84519. this.world.clear();
  84520. };
  84521. return OimoJSPlugin;
  84522. }());
  84523. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84524. })(BABYLON || (BABYLON = {}));
  84525. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84526. var BABYLON;
  84527. (function (BABYLON) {
  84528. /*
  84529. * Based on jsTGALoader - Javascript loader for TGA file
  84530. * By Vincent Thibault
  84531. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84532. */
  84533. var TGATools = /** @class */ (function () {
  84534. function TGATools() {
  84535. }
  84536. TGATools.GetTGAHeader = function (data) {
  84537. var offset = 0;
  84538. var header = {
  84539. id_length: data[offset++],
  84540. colormap_type: data[offset++],
  84541. image_type: data[offset++],
  84542. colormap_index: data[offset++] | data[offset++] << 8,
  84543. colormap_length: data[offset++] | data[offset++] << 8,
  84544. colormap_size: data[offset++],
  84545. origin: [
  84546. data[offset++] | data[offset++] << 8,
  84547. data[offset++] | data[offset++] << 8
  84548. ],
  84549. width: data[offset++] | data[offset++] << 8,
  84550. height: data[offset++] | data[offset++] << 8,
  84551. pixel_size: data[offset++],
  84552. flags: data[offset++]
  84553. };
  84554. return header;
  84555. };
  84556. TGATools.UploadContent = function (gl, data) {
  84557. // Not enough data to contain header ?
  84558. if (data.length < 19) {
  84559. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84560. return;
  84561. }
  84562. // Read Header
  84563. var offset = 18;
  84564. var header = TGATools.GetTGAHeader(data);
  84565. // Assume it's a valid Targa file.
  84566. if (header.id_length + offset > data.length) {
  84567. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84568. return;
  84569. }
  84570. // Skip not needed data
  84571. offset += header.id_length;
  84572. var use_rle = false;
  84573. var use_pal = false;
  84574. var use_grey = false;
  84575. // Get some informations.
  84576. switch (header.image_type) {
  84577. case TGATools._TYPE_RLE_INDEXED:
  84578. use_rle = true;
  84579. case TGATools._TYPE_INDEXED:
  84580. use_pal = true;
  84581. break;
  84582. case TGATools._TYPE_RLE_RGB:
  84583. use_rle = true;
  84584. case TGATools._TYPE_RGB:
  84585. // use_rgb = true;
  84586. break;
  84587. case TGATools._TYPE_RLE_GREY:
  84588. use_rle = true;
  84589. case TGATools._TYPE_GREY:
  84590. use_grey = true;
  84591. break;
  84592. }
  84593. var pixel_data;
  84594. // var numAlphaBits = header.flags & 0xf;
  84595. var pixel_size = header.pixel_size >> 3;
  84596. var pixel_total = header.width * header.height * pixel_size;
  84597. // Read palettes
  84598. var palettes;
  84599. if (use_pal) {
  84600. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84601. }
  84602. // Read LRE
  84603. if (use_rle) {
  84604. pixel_data = new Uint8Array(pixel_total);
  84605. var c, count, i;
  84606. var localOffset = 0;
  84607. var pixels = new Uint8Array(pixel_size);
  84608. while (offset < pixel_total && localOffset < pixel_total) {
  84609. c = data[offset++];
  84610. count = (c & 0x7f) + 1;
  84611. // RLE pixels
  84612. if (c & 0x80) {
  84613. // Bind pixel tmp array
  84614. for (i = 0; i < pixel_size; ++i) {
  84615. pixels[i] = data[offset++];
  84616. }
  84617. // Copy pixel array
  84618. for (i = 0; i < count; ++i) {
  84619. pixel_data.set(pixels, localOffset + i * pixel_size);
  84620. }
  84621. localOffset += pixel_size * count;
  84622. }
  84623. // Raw pixels
  84624. else {
  84625. count *= pixel_size;
  84626. for (i = 0; i < count; ++i) {
  84627. pixel_data[localOffset + i] = data[offset++];
  84628. }
  84629. localOffset += count;
  84630. }
  84631. }
  84632. }
  84633. // RAW Pixels
  84634. else {
  84635. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84636. }
  84637. // Load to texture
  84638. var x_start, y_start, x_step, y_step, y_end, x_end;
  84639. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84640. default:
  84641. case TGATools._ORIGIN_UL:
  84642. x_start = 0;
  84643. x_step = 1;
  84644. x_end = header.width;
  84645. y_start = 0;
  84646. y_step = 1;
  84647. y_end = header.height;
  84648. break;
  84649. case TGATools._ORIGIN_BL:
  84650. x_start = 0;
  84651. x_step = 1;
  84652. x_end = header.width;
  84653. y_start = header.height - 1;
  84654. y_step = -1;
  84655. y_end = -1;
  84656. break;
  84657. case TGATools._ORIGIN_UR:
  84658. x_start = header.width - 1;
  84659. x_step = -1;
  84660. x_end = -1;
  84661. y_start = 0;
  84662. y_step = 1;
  84663. y_end = header.height;
  84664. break;
  84665. case TGATools._ORIGIN_BR:
  84666. x_start = header.width - 1;
  84667. x_step = -1;
  84668. x_end = -1;
  84669. y_start = header.height - 1;
  84670. y_step = -1;
  84671. y_end = -1;
  84672. break;
  84673. }
  84674. // Load the specify method
  84675. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84676. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84677. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84678. };
  84679. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84680. var image = pixel_data, colormap = palettes;
  84681. var width = header.width, height = header.height;
  84682. var color, i = 0, x, y;
  84683. var imageData = new Uint8Array(width * height * 4);
  84684. for (y = y_start; y !== y_end; y += y_step) {
  84685. for (x = x_start; x !== x_end; x += x_step, i++) {
  84686. color = image[i];
  84687. imageData[(x + width * y) * 4 + 3] = 255;
  84688. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84689. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84690. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84691. }
  84692. }
  84693. return imageData;
  84694. };
  84695. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84696. var image = pixel_data;
  84697. var width = header.width, height = header.height;
  84698. var color, i = 0, x, y;
  84699. var imageData = new Uint8Array(width * height * 4);
  84700. for (y = y_start; y !== y_end; y += y_step) {
  84701. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84702. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84703. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84704. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84705. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84706. imageData[(x + width * y) * 4 + 0] = r;
  84707. imageData[(x + width * y) * 4 + 1] = g;
  84708. imageData[(x + width * y) * 4 + 2] = b;
  84709. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84710. }
  84711. }
  84712. return imageData;
  84713. };
  84714. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84715. var image = pixel_data;
  84716. var width = header.width, height = header.height;
  84717. var i = 0, x, y;
  84718. var imageData = new Uint8Array(width * height * 4);
  84719. for (y = y_start; y !== y_end; y += y_step) {
  84720. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84721. imageData[(x + width * y) * 4 + 3] = 255;
  84722. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84723. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84724. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84725. }
  84726. }
  84727. return imageData;
  84728. };
  84729. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84730. var image = pixel_data;
  84731. var width = header.width, height = header.height;
  84732. var i = 0, x, y;
  84733. var imageData = new Uint8Array(width * height * 4);
  84734. for (y = y_start; y !== y_end; y += y_step) {
  84735. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84736. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84737. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84738. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84739. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84740. }
  84741. }
  84742. return imageData;
  84743. };
  84744. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84745. var image = pixel_data;
  84746. var width = header.width, height = header.height;
  84747. var color, i = 0, x, y;
  84748. var imageData = new Uint8Array(width * height * 4);
  84749. for (y = y_start; y !== y_end; y += y_step) {
  84750. for (x = x_start; x !== x_end; x += x_step, i++) {
  84751. color = image[i];
  84752. imageData[(x + width * y) * 4 + 0] = color;
  84753. imageData[(x + width * y) * 4 + 1] = color;
  84754. imageData[(x + width * y) * 4 + 2] = color;
  84755. imageData[(x + width * y) * 4 + 3] = 255;
  84756. }
  84757. }
  84758. return imageData;
  84759. };
  84760. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84761. var image = pixel_data;
  84762. var width = header.width, height = header.height;
  84763. var i = 0, x, y;
  84764. var imageData = new Uint8Array(width * height * 4);
  84765. for (y = y_start; y !== y_end; y += y_step) {
  84766. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84767. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84768. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84769. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84770. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84771. }
  84772. }
  84773. return imageData;
  84774. };
  84775. //private static _TYPE_NO_DATA = 0;
  84776. TGATools._TYPE_INDEXED = 1;
  84777. TGATools._TYPE_RGB = 2;
  84778. TGATools._TYPE_GREY = 3;
  84779. TGATools._TYPE_RLE_INDEXED = 9;
  84780. TGATools._TYPE_RLE_RGB = 10;
  84781. TGATools._TYPE_RLE_GREY = 11;
  84782. TGATools._ORIGIN_MASK = 0x30;
  84783. TGATools._ORIGIN_SHIFT = 0x04;
  84784. TGATools._ORIGIN_BL = 0x00;
  84785. TGATools._ORIGIN_BR = 0x01;
  84786. TGATools._ORIGIN_UL = 0x02;
  84787. TGATools._ORIGIN_UR = 0x03;
  84788. return TGATools;
  84789. }());
  84790. BABYLON.TGATools = TGATools;
  84791. })(BABYLON || (BABYLON = {}));
  84792. //# sourceMappingURL=babylon.tga.js.map
  84793. var BABYLON;
  84794. (function (BABYLON) {
  84795. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84796. // All values and structures referenced from:
  84797. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84798. var DDS_MAGIC = 0x20534444;
  84799. var
  84800. //DDSD_CAPS = 0x1,
  84801. //DDSD_HEIGHT = 0x2,
  84802. //DDSD_WIDTH = 0x4,
  84803. //DDSD_PITCH = 0x8,
  84804. //DDSD_PIXELFORMAT = 0x1000,
  84805. DDSD_MIPMAPCOUNT = 0x20000;
  84806. //DDSD_LINEARSIZE = 0x80000,
  84807. //DDSD_DEPTH = 0x800000;
  84808. // var DDSCAPS_COMPLEX = 0x8,
  84809. // DDSCAPS_MIPMAP = 0x400000,
  84810. // DDSCAPS_TEXTURE = 0x1000;
  84811. var DDSCAPS2_CUBEMAP = 0x200;
  84812. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84813. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84814. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84815. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84816. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84817. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84818. // DDSCAPS2_VOLUME = 0x200000;
  84819. var
  84820. //DDPF_ALPHAPIXELS = 0x1,
  84821. //DDPF_ALPHA = 0x2,
  84822. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84823. //DDPF_YUV = 0x200,
  84824. DDPF_LUMINANCE = 0x20000;
  84825. function FourCCToInt32(value) {
  84826. return value.charCodeAt(0) +
  84827. (value.charCodeAt(1) << 8) +
  84828. (value.charCodeAt(2) << 16) +
  84829. (value.charCodeAt(3) << 24);
  84830. }
  84831. function Int32ToFourCC(value) {
  84832. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84833. }
  84834. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84835. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84836. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84837. var FOURCC_DX10 = FourCCToInt32("DX10");
  84838. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84839. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84840. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84841. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84842. var headerLengthInt = 31; // The header length in 32 bit ints
  84843. // Offsets into the header array
  84844. var off_magic = 0;
  84845. var off_size = 1;
  84846. var off_flags = 2;
  84847. var off_height = 3;
  84848. var off_width = 4;
  84849. var off_mipmapCount = 7;
  84850. var off_pfFlags = 20;
  84851. var off_pfFourCC = 21;
  84852. var off_RGBbpp = 22;
  84853. var off_RMask = 23;
  84854. var off_GMask = 24;
  84855. var off_BMask = 25;
  84856. var off_AMask = 26;
  84857. // var off_caps1 = 27;
  84858. var off_caps2 = 28;
  84859. // var off_caps3 = 29;
  84860. // var off_caps4 = 30;
  84861. var off_dxgiFormat = 32;
  84862. ;
  84863. var DDSTools = /** @class */ (function () {
  84864. function DDSTools() {
  84865. }
  84866. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84867. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84868. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84869. var mipmapCount = 1;
  84870. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84871. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84872. }
  84873. var fourCC = header[off_pfFourCC];
  84874. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84875. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84876. switch (fourCC) {
  84877. case FOURCC_D3DFMT_R16G16B16A16F:
  84878. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84879. break;
  84880. case FOURCC_D3DFMT_R32G32B32A32F:
  84881. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84882. break;
  84883. case FOURCC_DX10:
  84884. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84885. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84886. break;
  84887. }
  84888. }
  84889. return {
  84890. width: header[off_width],
  84891. height: header[off_height],
  84892. mipmapCount: mipmapCount,
  84893. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84894. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84895. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84896. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84897. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84898. dxgiFormat: dxgiFormat,
  84899. textureType: textureType
  84900. };
  84901. };
  84902. DDSTools._ToHalfFloat = function (value) {
  84903. if (!DDSTools._FloatView) {
  84904. DDSTools._FloatView = new Float32Array(1);
  84905. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84906. }
  84907. DDSTools._FloatView[0] = value;
  84908. var x = DDSTools._Int32View[0];
  84909. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84910. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84911. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84912. /* If zero, or denormal, or exponent underflows too much for a denormal
  84913. * half, return signed zero. */
  84914. if (e < 103) {
  84915. return bits;
  84916. }
  84917. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84918. if (e > 142) {
  84919. bits |= 0x7c00;
  84920. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84921. * not Inf, so make sure we set one mantissa bit too. */
  84922. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84923. return bits;
  84924. }
  84925. /* If exponent underflows but not too much, return a denormal */
  84926. if (e < 113) {
  84927. m |= 0x0800;
  84928. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84929. * to 1, which is OK. */
  84930. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84931. return bits;
  84932. }
  84933. bits |= ((e - 112) << 10) | (m >> 1);
  84934. bits += m & 1;
  84935. return bits;
  84936. };
  84937. DDSTools._FromHalfFloat = function (value) {
  84938. var s = (value & 0x8000) >> 15;
  84939. var e = (value & 0x7C00) >> 10;
  84940. var f = value & 0x03FF;
  84941. if (e === 0) {
  84942. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84943. }
  84944. else if (e == 0x1F) {
  84945. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84946. }
  84947. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84948. };
  84949. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84950. var destArray = new Float32Array(dataLength);
  84951. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84952. var index = 0;
  84953. for (var y = 0; y < height; y++) {
  84954. for (var x = 0; x < width; x++) {
  84955. var srcPos = (x + y * width) * 4;
  84956. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84957. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84958. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84959. if (DDSTools.StoreLODInAlphaChannel) {
  84960. destArray[index + 3] = lod;
  84961. }
  84962. else {
  84963. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84964. }
  84965. index += 4;
  84966. }
  84967. }
  84968. return destArray;
  84969. };
  84970. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84971. if (DDSTools.StoreLODInAlphaChannel) {
  84972. var destArray = new Uint16Array(dataLength);
  84973. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84974. var index = 0;
  84975. for (var y = 0; y < height; y++) {
  84976. for (var x = 0; x < width; x++) {
  84977. var srcPos = (x + y * width) * 4;
  84978. destArray[index] = srcData[srcPos];
  84979. destArray[index + 1] = srcData[srcPos + 1];
  84980. destArray[index + 2] = srcData[srcPos + 2];
  84981. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84982. index += 4;
  84983. }
  84984. }
  84985. return destArray;
  84986. }
  84987. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84988. };
  84989. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84990. if (DDSTools.StoreLODInAlphaChannel) {
  84991. var destArray = new Float32Array(dataLength);
  84992. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84993. var index = 0;
  84994. for (var y = 0; y < height; y++) {
  84995. for (var x = 0; x < width; x++) {
  84996. var srcPos = (x + y * width) * 4;
  84997. destArray[index] = srcData[srcPos];
  84998. destArray[index + 1] = srcData[srcPos + 1];
  84999. destArray[index + 2] = srcData[srcPos + 2];
  85000. destArray[index + 3] = lod;
  85001. index += 4;
  85002. }
  85003. }
  85004. return destArray;
  85005. }
  85006. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85007. };
  85008. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85009. var destArray = new Uint8Array(dataLength);
  85010. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85011. var index = 0;
  85012. for (var y = 0; y < height; y++) {
  85013. for (var x = 0; x < width; x++) {
  85014. var srcPos = (x + y * width) * 4;
  85015. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85016. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85017. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85018. if (DDSTools.StoreLODInAlphaChannel) {
  85019. destArray[index + 3] = lod;
  85020. }
  85021. else {
  85022. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85023. }
  85024. index += 4;
  85025. }
  85026. }
  85027. return destArray;
  85028. };
  85029. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85030. var destArray = new Uint8Array(dataLength);
  85031. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85032. var index = 0;
  85033. for (var y = 0; y < height; y++) {
  85034. for (var x = 0; x < width; x++) {
  85035. var srcPos = (x + y * width) * 4;
  85036. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85037. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85038. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85039. if (DDSTools.StoreLODInAlphaChannel) {
  85040. destArray[index + 3] = lod;
  85041. }
  85042. else {
  85043. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85044. }
  85045. index += 4;
  85046. }
  85047. }
  85048. return destArray;
  85049. };
  85050. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85051. var byteArray = new Uint8Array(dataLength);
  85052. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85053. var index = 0;
  85054. for (var y = 0; y < height; y++) {
  85055. for (var x = 0; x < width; x++) {
  85056. var srcPos = (x + y * width) * 4;
  85057. byteArray[index] = srcData[srcPos + rOffset];
  85058. byteArray[index + 1] = srcData[srcPos + gOffset];
  85059. byteArray[index + 2] = srcData[srcPos + bOffset];
  85060. byteArray[index + 3] = srcData[srcPos + aOffset];
  85061. index += 4;
  85062. }
  85063. }
  85064. return byteArray;
  85065. };
  85066. DDSTools._ExtractLongWordOrder = function (value) {
  85067. if (value === 0 || value === 255 || value === -16777216) {
  85068. return 0;
  85069. }
  85070. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85071. };
  85072. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85073. var byteArray = new Uint8Array(dataLength);
  85074. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85075. var index = 0;
  85076. for (var y = 0; y < height; y++) {
  85077. for (var x = 0; x < width; x++) {
  85078. var srcPos = (x + y * width) * 3;
  85079. byteArray[index] = srcData[srcPos + rOffset];
  85080. byteArray[index + 1] = srcData[srcPos + gOffset];
  85081. byteArray[index + 2] = srcData[srcPos + bOffset];
  85082. index += 3;
  85083. }
  85084. }
  85085. return byteArray;
  85086. };
  85087. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85088. var byteArray = new Uint8Array(dataLength);
  85089. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85090. var index = 0;
  85091. for (var y = 0; y < height; y++) {
  85092. for (var x = 0; x < width; x++) {
  85093. var srcPos = (x + y * width);
  85094. byteArray[index] = srcData[srcPos];
  85095. index++;
  85096. }
  85097. }
  85098. return byteArray;
  85099. };
  85100. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85101. if (lodIndex === void 0) { lodIndex = -1; }
  85102. var sphericalPolynomialFaces = null;
  85103. if (info.sphericalPolynomial) {
  85104. sphericalPolynomialFaces = new Array();
  85105. }
  85106. var ext = engine.getCaps().s3tc;
  85107. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85108. var fourCC, width, height, dataLength = 0, dataOffset;
  85109. var byteArray, mipmapCount, mip;
  85110. var internalFormat = 0;
  85111. var format = 0;
  85112. var blockBytes = 1;
  85113. if (header[off_magic] !== DDS_MAGIC) {
  85114. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85115. return;
  85116. }
  85117. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85118. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85119. return;
  85120. }
  85121. if (info.isCompressed && !ext) {
  85122. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85123. return;
  85124. }
  85125. var bpp = header[off_RGBbpp];
  85126. dataOffset = header[off_size] + 4;
  85127. var computeFormats = false;
  85128. if (info.isFourCC) {
  85129. fourCC = header[off_pfFourCC];
  85130. switch (fourCC) {
  85131. case FOURCC_DXT1:
  85132. blockBytes = 8;
  85133. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85134. break;
  85135. case FOURCC_DXT3:
  85136. blockBytes = 16;
  85137. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85138. break;
  85139. case FOURCC_DXT5:
  85140. blockBytes = 16;
  85141. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85142. break;
  85143. case FOURCC_D3DFMT_R16G16B16A16F:
  85144. computeFormats = true;
  85145. break;
  85146. case FOURCC_D3DFMT_R32G32B32A32F:
  85147. computeFormats = true;
  85148. break;
  85149. case FOURCC_DX10:
  85150. // There is an additionnal header so dataOffset need to be changed
  85151. dataOffset += 5 * 4; // 5 uints
  85152. var supported = false;
  85153. switch (info.dxgiFormat) {
  85154. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85155. computeFormats = true;
  85156. supported = true;
  85157. break;
  85158. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85159. info.isRGB = true;
  85160. info.isFourCC = false;
  85161. bpp = 32;
  85162. supported = true;
  85163. break;
  85164. }
  85165. if (supported) {
  85166. break;
  85167. }
  85168. default:
  85169. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85170. return;
  85171. }
  85172. }
  85173. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85174. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85175. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85176. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85177. if (computeFormats) {
  85178. format = engine._getWebGLTextureType(info.textureType);
  85179. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85180. }
  85181. mipmapCount = 1;
  85182. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85183. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85184. }
  85185. for (var face = 0; face < faces; face++) {
  85186. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85187. width = header[off_width];
  85188. height = header[off_height];
  85189. for (mip = 0; mip < mipmapCount; ++mip) {
  85190. if (lodIndex === -1 || lodIndex === mip) {
  85191. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85192. var i = (lodIndex === -1) ? mip : 0;
  85193. if (!info.isCompressed && info.isFourCC) {
  85194. dataLength = width * height * 4;
  85195. var floatArray = null;
  85196. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85197. if (bpp === 128) {
  85198. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85199. if (sphericalPolynomialFaces && i == 0) {
  85200. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85201. }
  85202. }
  85203. else if (bpp === 64) {
  85204. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85205. if (sphericalPolynomialFaces && i == 0) {
  85206. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85207. }
  85208. }
  85209. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85210. format = engine._getWebGLTextureType(info.textureType);
  85211. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85212. }
  85213. else {
  85214. if (bpp === 128) {
  85215. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85216. if (sphericalPolynomialFaces && i == 0) {
  85217. sphericalPolynomialFaces.push(floatArray);
  85218. }
  85219. }
  85220. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85221. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85222. if (sphericalPolynomialFaces && i == 0) {
  85223. sphericalPolynomialFaces.push(floatArray);
  85224. }
  85225. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85226. format = engine._getWebGLTextureType(info.textureType);
  85227. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85228. }
  85229. else { // 64
  85230. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85231. if (sphericalPolynomialFaces && i == 0) {
  85232. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85233. }
  85234. }
  85235. }
  85236. if (floatArray) {
  85237. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85238. }
  85239. }
  85240. else if (info.isRGB) {
  85241. if (bpp === 24) {
  85242. dataLength = width * height * 3;
  85243. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85244. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85245. }
  85246. else { // 32
  85247. dataLength = width * height * 4;
  85248. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85249. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85250. }
  85251. }
  85252. else if (info.isLuminance) {
  85253. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85254. var unpaddedRowSize = width;
  85255. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85256. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85257. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85258. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85259. }
  85260. else {
  85261. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85262. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85263. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85264. }
  85265. }
  85266. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85267. width *= 0.5;
  85268. height *= 0.5;
  85269. width = Math.max(1.0, width);
  85270. height = Math.max(1.0, height);
  85271. }
  85272. if (currentFace !== undefined) {
  85273. // Loading a single face
  85274. break;
  85275. }
  85276. }
  85277. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85278. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85279. size: header[off_width],
  85280. right: sphericalPolynomialFaces[0],
  85281. left: sphericalPolynomialFaces[1],
  85282. up: sphericalPolynomialFaces[2],
  85283. down: sphericalPolynomialFaces[3],
  85284. front: sphericalPolynomialFaces[4],
  85285. back: sphericalPolynomialFaces[5],
  85286. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85287. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85288. gammaSpace: false,
  85289. });
  85290. }
  85291. else {
  85292. info.sphericalPolynomial = undefined;
  85293. }
  85294. };
  85295. DDSTools.StoreLODInAlphaChannel = false;
  85296. return DDSTools;
  85297. }());
  85298. BABYLON.DDSTools = DDSTools;
  85299. })(BABYLON || (BABYLON = {}));
  85300. //# sourceMappingURL=babylon.dds.js.map
  85301. var BABYLON;
  85302. (function (BABYLON) {
  85303. /**
  85304. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85305. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85306. */
  85307. var KhronosTextureContainer = /** @class */ (function () {
  85308. /**
  85309. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85310. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85311. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85312. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85313. */
  85314. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85315. this.arrayBuffer = arrayBuffer;
  85316. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85317. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85318. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85319. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85320. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85321. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85322. BABYLON.Tools.Error("texture missing KTX identifier");
  85323. return;
  85324. }
  85325. // load the reset of the header in native 32 bit int
  85326. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85327. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85328. var oppositeEndianess = header[0] === 0x01020304;
  85329. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85330. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85331. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85332. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85333. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85334. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85335. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85336. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85337. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85338. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85339. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85340. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85341. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85342. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85343. if (this.glType !== 0) {
  85344. BABYLON.Tools.Error("only compressed formats currently supported");
  85345. return;
  85346. }
  85347. else {
  85348. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85349. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85350. }
  85351. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85352. BABYLON.Tools.Error("only 2D textures currently supported");
  85353. return;
  85354. }
  85355. if (this.numberOfArrayElements !== 0) {
  85356. BABYLON.Tools.Error("texture arrays not currently supported");
  85357. return;
  85358. }
  85359. if (this.numberOfFaces !== facesExpected) {
  85360. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85361. return;
  85362. }
  85363. // we now have a completely validated file, so could use existence of loadType as success
  85364. // would need to make this more elaborate & adjust checks above to support more than one load type
  85365. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85366. }
  85367. // not as fast hardware based, but will probably never need to use
  85368. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85369. return ((val & 0xFF) << 24)
  85370. | ((val & 0xFF00) << 8)
  85371. | ((val >> 8) & 0xFF00)
  85372. | ((val >> 24) & 0xFF);
  85373. };
  85374. /**
  85375. * It is assumed that the texture has already been created & is currently bound
  85376. */
  85377. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85378. switch (this.loadType) {
  85379. case KhronosTextureContainer.COMPRESSED_2D:
  85380. this._upload2DCompressedLevels(gl, loadMipmaps);
  85381. break;
  85382. case KhronosTextureContainer.TEX_2D:
  85383. case KhronosTextureContainer.COMPRESSED_3D:
  85384. case KhronosTextureContainer.TEX_3D:
  85385. }
  85386. };
  85387. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85388. // initialize width & height for level 1
  85389. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85390. var width = this.pixelWidth;
  85391. var height = this.pixelHeight;
  85392. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85393. for (var level = 0; level < mipmapCount; level++) {
  85394. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85395. for (var face = 0; face < this.numberOfFaces; face++) {
  85396. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85397. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85398. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85399. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85400. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85401. }
  85402. width = Math.max(1.0, width * 0.5);
  85403. height = Math.max(1.0, height * 0.5);
  85404. }
  85405. };
  85406. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85407. // load types
  85408. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85409. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85410. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85411. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85412. return KhronosTextureContainer;
  85413. }());
  85414. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85415. })(BABYLON || (BABYLON = {}));
  85416. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85417. var BABYLON;
  85418. (function (BABYLON) {
  85419. var Debug;
  85420. (function (Debug) {
  85421. /**
  85422. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85423. */
  85424. var SkeletonViewer = /** @class */ (function () {
  85425. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85426. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85427. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85428. this.skeleton = skeleton;
  85429. this.mesh = mesh;
  85430. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85431. this.renderingGroupId = renderingGroupId;
  85432. this.color = BABYLON.Color3.White();
  85433. this._debugLines = new Array();
  85434. this._isEnabled = false;
  85435. this._scene = scene;
  85436. this.update();
  85437. this._renderFunction = this.update.bind(this);
  85438. }
  85439. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85440. get: function () {
  85441. return this._isEnabled;
  85442. },
  85443. set: function (value) {
  85444. if (this._isEnabled === value) {
  85445. return;
  85446. }
  85447. this._isEnabled = value;
  85448. if (value) {
  85449. this._scene.registerBeforeRender(this._renderFunction);
  85450. }
  85451. else {
  85452. this._scene.unregisterBeforeRender(this._renderFunction);
  85453. }
  85454. },
  85455. enumerable: true,
  85456. configurable: true
  85457. });
  85458. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85459. if (x === void 0) { x = 0; }
  85460. if (y === void 0) { y = 0; }
  85461. if (z === void 0) { z = 0; }
  85462. var tmat = BABYLON.Tmp.Matrix[0];
  85463. var parentBone = bone.getParent();
  85464. tmat.copyFrom(bone.getLocalMatrix());
  85465. if (x !== 0 || y !== 0 || z !== 0) {
  85466. var tmat2 = BABYLON.Tmp.Matrix[1];
  85467. BABYLON.Matrix.IdentityToRef(tmat2);
  85468. tmat2.m[12] = x;
  85469. tmat2.m[13] = y;
  85470. tmat2.m[14] = z;
  85471. tmat2.multiplyToRef(tmat, tmat);
  85472. }
  85473. if (parentBone) {
  85474. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85475. }
  85476. tmat.multiplyToRef(meshMat, tmat);
  85477. position.x = tmat.m[12];
  85478. position.y = tmat.m[13];
  85479. position.z = tmat.m[14];
  85480. };
  85481. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85482. var len = bones.length;
  85483. var meshPos = this.mesh.position;
  85484. for (var i = 0; i < len; i++) {
  85485. var bone = bones[i];
  85486. var points = this._debugLines[i];
  85487. if (!points) {
  85488. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85489. this._debugLines[i] = points;
  85490. }
  85491. this._getBonePosition(points[0], bone, meshMat);
  85492. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85493. points[0].subtractInPlace(meshPos);
  85494. points[1].subtractInPlace(meshPos);
  85495. }
  85496. };
  85497. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85498. var len = bones.length;
  85499. var boneNum = 0;
  85500. var meshPos = this.mesh.position;
  85501. for (var i = len - 1; i >= 0; i--) {
  85502. var childBone = bones[i];
  85503. var parentBone = childBone.getParent();
  85504. if (!parentBone) {
  85505. continue;
  85506. }
  85507. var points = this._debugLines[boneNum];
  85508. if (!points) {
  85509. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85510. this._debugLines[boneNum] = points;
  85511. }
  85512. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85513. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85514. points[0].subtractInPlace(meshPos);
  85515. points[1].subtractInPlace(meshPos);
  85516. boneNum++;
  85517. }
  85518. };
  85519. SkeletonViewer.prototype.update = function () {
  85520. if (this.autoUpdateBonesMatrices) {
  85521. this.skeleton.computeAbsoluteTransforms();
  85522. }
  85523. if (this.skeleton.bones[0].length === undefined) {
  85524. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85525. }
  85526. else {
  85527. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85528. }
  85529. if (!this._debugMesh) {
  85530. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85531. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85532. }
  85533. else {
  85534. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85535. }
  85536. this._debugMesh.position.copyFrom(this.mesh.position);
  85537. this._debugMesh.color = this.color;
  85538. };
  85539. SkeletonViewer.prototype.dispose = function () {
  85540. if (this._debugMesh) {
  85541. this.isEnabled = false;
  85542. this._debugMesh.dispose();
  85543. this._debugMesh = null;
  85544. }
  85545. };
  85546. return SkeletonViewer;
  85547. }());
  85548. Debug.SkeletonViewer = SkeletonViewer;
  85549. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85550. })(BABYLON || (BABYLON = {}));
  85551. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85552. /**
  85553. * Module Debug contains the (visual) components to debug a scene correctly
  85554. */
  85555. var BABYLON;
  85556. (function (BABYLON) {
  85557. var Debug;
  85558. (function (Debug) {
  85559. /**
  85560. * The Axes viewer will show 3 axes in a specific point in space
  85561. */
  85562. var AxesViewer = /** @class */ (function () {
  85563. function AxesViewer(scene, scaleLines) {
  85564. if (scaleLines === void 0) { scaleLines = 1; }
  85565. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85566. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85567. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85568. this.scaleLines = 1;
  85569. this.scaleLines = scaleLines;
  85570. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85571. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85572. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85573. this._xmesh.renderingGroupId = 2;
  85574. this._ymesh.renderingGroupId = 2;
  85575. this._zmesh.renderingGroupId = 2;
  85576. this._xmesh.material.checkReadyOnlyOnce = true;
  85577. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85578. this._ymesh.material.checkReadyOnlyOnce = true;
  85579. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85580. this._zmesh.material.checkReadyOnlyOnce = true;
  85581. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85582. this.scene = scene;
  85583. }
  85584. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85585. var scaleLines = this.scaleLines;
  85586. if (this._xmesh) {
  85587. this._xmesh.position.copyFrom(position);
  85588. }
  85589. if (this._ymesh) {
  85590. this._ymesh.position.copyFrom(position);
  85591. }
  85592. if (this._zmesh) {
  85593. this._zmesh.position.copyFrom(position);
  85594. }
  85595. var point2 = this._xline[1];
  85596. point2.x = xaxis.x * scaleLines;
  85597. point2.y = xaxis.y * scaleLines;
  85598. point2.z = xaxis.z * scaleLines;
  85599. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85600. point2 = this._yline[1];
  85601. point2.x = yaxis.x * scaleLines;
  85602. point2.y = yaxis.y * scaleLines;
  85603. point2.z = yaxis.z * scaleLines;
  85604. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85605. point2 = this._zline[1];
  85606. point2.x = zaxis.x * scaleLines;
  85607. point2.y = zaxis.y * scaleLines;
  85608. point2.z = zaxis.z * scaleLines;
  85609. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85610. };
  85611. AxesViewer.prototype.dispose = function () {
  85612. if (this._xmesh) {
  85613. this._xmesh.dispose();
  85614. }
  85615. if (this._ymesh) {
  85616. this._ymesh.dispose();
  85617. }
  85618. if (this._zmesh) {
  85619. this._zmesh.dispose();
  85620. }
  85621. this._xmesh = null;
  85622. this._ymesh = null;
  85623. this._zmesh = null;
  85624. this.scene = null;
  85625. };
  85626. return AxesViewer;
  85627. }());
  85628. Debug.AxesViewer = AxesViewer;
  85629. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85630. })(BABYLON || (BABYLON = {}));
  85631. //# sourceMappingURL=babylon.axesViewer.js.map
  85632. var BABYLON;
  85633. (function (BABYLON) {
  85634. var Debug;
  85635. (function (Debug) {
  85636. /**
  85637. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85638. */
  85639. var BoneAxesViewer = /** @class */ (function (_super) {
  85640. __extends(BoneAxesViewer, _super);
  85641. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85642. if (scaleLines === void 0) { scaleLines = 1; }
  85643. var _this = _super.call(this, scene, scaleLines) || this;
  85644. _this.pos = BABYLON.Vector3.Zero();
  85645. _this.xaxis = BABYLON.Vector3.Zero();
  85646. _this.yaxis = BABYLON.Vector3.Zero();
  85647. _this.zaxis = BABYLON.Vector3.Zero();
  85648. _this.mesh = mesh;
  85649. _this.bone = bone;
  85650. return _this;
  85651. }
  85652. BoneAxesViewer.prototype.update = function () {
  85653. if (!this.mesh || !this.bone) {
  85654. return;
  85655. }
  85656. var bone = this.bone;
  85657. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85658. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85659. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85660. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85661. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85662. };
  85663. BoneAxesViewer.prototype.dispose = function () {
  85664. if (this.mesh) {
  85665. this.mesh = null;
  85666. this.bone = null;
  85667. _super.prototype.dispose.call(this);
  85668. }
  85669. };
  85670. return BoneAxesViewer;
  85671. }(Debug.AxesViewer));
  85672. Debug.BoneAxesViewer = BoneAxesViewer;
  85673. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85674. })(BABYLON || (BABYLON = {}));
  85675. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85676. var BABYLON;
  85677. (function (BABYLON) {
  85678. var RayHelper = /** @class */ (function () {
  85679. function RayHelper(ray) {
  85680. this.ray = ray;
  85681. }
  85682. RayHelper.CreateAndShow = function (ray, scene, color) {
  85683. var helper = new RayHelper(ray);
  85684. helper.show(scene, color);
  85685. return helper;
  85686. };
  85687. RayHelper.prototype.show = function (scene, color) {
  85688. if (!this._renderFunction && this.ray) {
  85689. var ray = this.ray;
  85690. this._renderFunction = this._render.bind(this);
  85691. this._scene = scene;
  85692. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85693. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85694. if (this._renderFunction) {
  85695. this._scene.registerBeforeRender(this._renderFunction);
  85696. }
  85697. }
  85698. if (color && this._renderLine) {
  85699. this._renderLine.color.copyFrom(color);
  85700. }
  85701. };
  85702. RayHelper.prototype.hide = function () {
  85703. if (this._renderFunction && this._scene) {
  85704. this._scene.unregisterBeforeRender(this._renderFunction);
  85705. this._scene = null;
  85706. this._renderFunction = null;
  85707. if (this._renderLine) {
  85708. this._renderLine.dispose();
  85709. this._renderLine = null;
  85710. }
  85711. this._renderPoints = [];
  85712. }
  85713. };
  85714. RayHelper.prototype._render = function () {
  85715. var ray = this.ray;
  85716. if (!ray) {
  85717. return;
  85718. }
  85719. var point = this._renderPoints[1];
  85720. var len = Math.min(ray.length, 1000000);
  85721. point.copyFrom(ray.direction);
  85722. point.scaleInPlace(len);
  85723. point.addInPlace(ray.origin);
  85724. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85725. };
  85726. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85727. this._attachedToMesh = mesh;
  85728. var ray = this.ray;
  85729. if (!ray) {
  85730. return;
  85731. }
  85732. if (!ray.direction) {
  85733. ray.direction = BABYLON.Vector3.Zero();
  85734. }
  85735. if (!ray.origin) {
  85736. ray.origin = BABYLON.Vector3.Zero();
  85737. }
  85738. if (length) {
  85739. ray.length = length;
  85740. }
  85741. if (!meshSpaceOrigin) {
  85742. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85743. }
  85744. if (!meshSpaceDirection) {
  85745. // -1 so that this will work with Mesh.lookAt
  85746. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85747. }
  85748. if (!this._meshSpaceDirection) {
  85749. this._meshSpaceDirection = meshSpaceDirection.clone();
  85750. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85751. }
  85752. else {
  85753. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85754. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85755. }
  85756. if (!this._updateToMeshFunction) {
  85757. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85758. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85759. }
  85760. this._updateToMesh();
  85761. };
  85762. RayHelper.prototype.detachFromMesh = function () {
  85763. if (this._attachedToMesh) {
  85764. if (this._updateToMeshFunction) {
  85765. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85766. }
  85767. this._attachedToMesh = null;
  85768. this._updateToMeshFunction = null;
  85769. }
  85770. };
  85771. RayHelper.prototype._updateToMesh = function () {
  85772. var ray = this.ray;
  85773. if (!this._attachedToMesh || !ray) {
  85774. return;
  85775. }
  85776. if (this._attachedToMesh._isDisposed) {
  85777. this.detachFromMesh();
  85778. return;
  85779. }
  85780. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85781. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85782. };
  85783. RayHelper.prototype.dispose = function () {
  85784. this.hide();
  85785. this.detachFromMesh();
  85786. this.ray = null;
  85787. };
  85788. return RayHelper;
  85789. }());
  85790. BABYLON.RayHelper = RayHelper;
  85791. })(BABYLON || (BABYLON = {}));
  85792. //# sourceMappingURL=babylon.rayHelper.js.map
  85793. var BABYLON;
  85794. (function (BABYLON) {
  85795. // load the inspector using require, if not present in the global namespace.
  85796. var DebugLayer = /** @class */ (function () {
  85797. function DebugLayer(scene) {
  85798. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85799. this._scene = scene;
  85800. // load inspector using require, if it doesn't exist on the global namespace.
  85801. }
  85802. /** Creates the inspector window. */
  85803. DebugLayer.prototype._createInspector = function (config) {
  85804. if (config === void 0) { config = {}; }
  85805. var popup = config.popup || false;
  85806. var initialTab = config.initialTab || 0;
  85807. var parentElement = config.parentElement || null;
  85808. if (!this._inspector) {
  85809. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85810. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85811. } // else nothing to do,; instance is already existing
  85812. };
  85813. DebugLayer.prototype.isVisible = function () {
  85814. if (!this._inspector) {
  85815. return false;
  85816. }
  85817. return true;
  85818. };
  85819. DebugLayer.prototype.hide = function () {
  85820. if (this._inspector) {
  85821. try {
  85822. this._inspector.dispose();
  85823. }
  85824. catch (e) {
  85825. // If the inspector has been removed directly from the inspector tool
  85826. }
  85827. this._inspector = null;
  85828. }
  85829. };
  85830. DebugLayer.prototype.show = function (config) {
  85831. if (config === void 0) { config = {}; }
  85832. if (typeof this.BJSINSPECTOR == 'undefined') {
  85833. // Load inspector and add it to the DOM
  85834. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85835. }
  85836. else {
  85837. // Otherwise creates the inspector
  85838. this._createInspector(config);
  85839. }
  85840. };
  85841. /**
  85842. * Gets the active tab
  85843. * @return the index of the active tab or -1 if the inspector is hidden
  85844. */
  85845. DebugLayer.prototype.getActiveTab = function () {
  85846. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  85847. };
  85848. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85849. return DebugLayer;
  85850. }());
  85851. BABYLON.DebugLayer = DebugLayer;
  85852. })(BABYLON || (BABYLON = {}));
  85853. //# sourceMappingURL=babylon.debugLayer.js.map
  85854. var BABYLON;
  85855. (function (BABYLON) {
  85856. var Debug;
  85857. (function (Debug) {
  85858. /**
  85859. * Used to show the physics impostor around the specific mesh.
  85860. */
  85861. var PhysicsViewer = /** @class */ (function () {
  85862. function PhysicsViewer(scene) {
  85863. this._impostors = [];
  85864. this._meshes = [];
  85865. this._numMeshes = 0;
  85866. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85867. var physicEngine = this._scene.getPhysicsEngine();
  85868. if (physicEngine) {
  85869. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85870. }
  85871. }
  85872. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85873. var plugin = this._physicsEnginePlugin;
  85874. for (var i = 0; i < this._numMeshes; i++) {
  85875. var impostor = this._impostors[i];
  85876. if (!impostor) {
  85877. continue;
  85878. }
  85879. if (impostor.isDisposed) {
  85880. this.hideImpostor(this._impostors[i--]);
  85881. }
  85882. else {
  85883. var mesh = this._meshes[i];
  85884. if (mesh && plugin) {
  85885. plugin.syncMeshWithImpostor(mesh, impostor);
  85886. }
  85887. }
  85888. }
  85889. };
  85890. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85891. if (!this._scene) {
  85892. return;
  85893. }
  85894. for (var i = 0; i < this._numMeshes; i++) {
  85895. if (this._impostors[i] == impostor) {
  85896. return;
  85897. }
  85898. }
  85899. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85900. if (debugMesh) {
  85901. this._impostors[this._numMeshes] = impostor;
  85902. this._meshes[this._numMeshes] = debugMesh;
  85903. if (this._numMeshes === 0) {
  85904. this._renderFunction = this._updateDebugMeshes.bind(this);
  85905. this._scene.registerBeforeRender(this._renderFunction);
  85906. }
  85907. this._numMeshes++;
  85908. }
  85909. };
  85910. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85911. if (!impostor || !this._scene) {
  85912. return;
  85913. }
  85914. var removed = false;
  85915. for (var i = 0; i < this._numMeshes; i++) {
  85916. if (this._impostors[i] == impostor) {
  85917. var mesh = this._meshes[i];
  85918. if (!mesh) {
  85919. continue;
  85920. }
  85921. this._scene.removeMesh(mesh);
  85922. mesh.dispose();
  85923. this._numMeshes--;
  85924. if (this._numMeshes > 0) {
  85925. this._meshes[i] = this._meshes[this._numMeshes];
  85926. this._impostors[i] = this._impostors[this._numMeshes];
  85927. this._meshes[this._numMeshes] = null;
  85928. this._impostors[this._numMeshes] = null;
  85929. }
  85930. else {
  85931. this._meshes[0] = null;
  85932. this._impostors[0] = null;
  85933. }
  85934. removed = true;
  85935. break;
  85936. }
  85937. }
  85938. if (removed && this._numMeshes === 0) {
  85939. this._scene.unregisterBeforeRender(this._renderFunction);
  85940. }
  85941. };
  85942. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85943. if (!this._debugMaterial) {
  85944. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85945. this._debugMaterial.wireframe = true;
  85946. }
  85947. return this._debugMaterial;
  85948. };
  85949. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85950. if (!this._debugBoxMesh) {
  85951. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85952. this._debugBoxMesh.renderingGroupId = 1;
  85953. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85954. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85955. scene.removeMesh(this._debugBoxMesh);
  85956. }
  85957. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85958. };
  85959. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85960. if (!this._debugSphereMesh) {
  85961. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85962. this._debugSphereMesh.renderingGroupId = 1;
  85963. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85964. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85965. scene.removeMesh(this._debugSphereMesh);
  85966. }
  85967. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85968. };
  85969. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85970. var mesh = null;
  85971. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85972. mesh = this._getDebugBoxMesh(scene);
  85973. impostor.getBoxSizeToRef(mesh.scaling);
  85974. }
  85975. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85976. mesh = this._getDebugSphereMesh(scene);
  85977. var radius = impostor.getRadius();
  85978. mesh.scaling.x = radius * 2;
  85979. mesh.scaling.y = radius * 2;
  85980. mesh.scaling.z = radius * 2;
  85981. }
  85982. return mesh;
  85983. };
  85984. PhysicsViewer.prototype.dispose = function () {
  85985. for (var i = 0; i < this._numMeshes; i++) {
  85986. this.hideImpostor(this._impostors[i]);
  85987. }
  85988. if (this._debugBoxMesh) {
  85989. this._debugBoxMesh.dispose();
  85990. }
  85991. if (this._debugSphereMesh) {
  85992. this._debugSphereMesh.dispose();
  85993. }
  85994. if (this._debugMaterial) {
  85995. this._debugMaterial.dispose();
  85996. }
  85997. this._impostors.length = 0;
  85998. this._scene = null;
  85999. this._physicsEnginePlugin = null;
  86000. };
  86001. return PhysicsViewer;
  86002. }());
  86003. Debug.PhysicsViewer = PhysicsViewer;
  86004. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86005. })(BABYLON || (BABYLON = {}));
  86006. //# sourceMappingURL=babylon.physicsViewer.js.map
  86007. var BABYLON;
  86008. (function (BABYLON) {
  86009. var BoundingBoxRenderer = /** @class */ (function () {
  86010. function BoundingBoxRenderer(scene) {
  86011. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86012. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86013. this.showBackLines = true;
  86014. this.renderList = new BABYLON.SmartArray(32);
  86015. this._vertexBuffers = {};
  86016. this._scene = scene;
  86017. }
  86018. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86019. if (this._colorShader) {
  86020. return;
  86021. }
  86022. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86023. attributes: [BABYLON.VertexBuffer.PositionKind],
  86024. uniforms: ["world", "viewProjection", "color"]
  86025. });
  86026. var engine = this._scene.getEngine();
  86027. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86029. this._createIndexBuffer();
  86030. };
  86031. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86032. var engine = this._scene.getEngine();
  86033. 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]);
  86034. };
  86035. BoundingBoxRenderer.prototype._rebuild = function () {
  86036. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86037. if (vb) {
  86038. vb._rebuild();
  86039. }
  86040. this._createIndexBuffer();
  86041. };
  86042. BoundingBoxRenderer.prototype.reset = function () {
  86043. this.renderList.reset();
  86044. };
  86045. BoundingBoxRenderer.prototype.render = function () {
  86046. if (this.renderList.length === 0) {
  86047. return;
  86048. }
  86049. this._prepareRessources();
  86050. if (!this._colorShader.isReady()) {
  86051. return;
  86052. }
  86053. var engine = this._scene.getEngine();
  86054. engine.setDepthWrite(false);
  86055. this._colorShader._preBind();
  86056. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86057. var boundingBox = this.renderList.data[boundingBoxIndex];
  86058. var min = boundingBox.minimum;
  86059. var max = boundingBox.maximum;
  86060. var diff = max.subtract(min);
  86061. var median = min.add(diff.scale(0.5));
  86062. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86063. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86064. .multiply(boundingBox.getWorldMatrix());
  86065. // VBOs
  86066. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86067. if (this.showBackLines) {
  86068. // Back
  86069. engine.setDepthFunctionToGreaterOrEqual();
  86070. this._scene.resetCachedMaterial();
  86071. this._colorShader.setColor4("color", this.backColor.toColor4());
  86072. this._colorShader.bind(worldMatrix);
  86073. // Draw order
  86074. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86075. }
  86076. // Front
  86077. engine.setDepthFunctionToLess();
  86078. this._scene.resetCachedMaterial();
  86079. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86080. this._colorShader.bind(worldMatrix);
  86081. // Draw order
  86082. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86083. }
  86084. this._colorShader.unbind();
  86085. engine.setDepthFunctionToLessOrEqual();
  86086. engine.setDepthWrite(true);
  86087. };
  86088. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86089. this._prepareRessources();
  86090. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86091. return;
  86092. }
  86093. var engine = this._scene.getEngine();
  86094. engine.setDepthWrite(false);
  86095. engine.setColorWrite(false);
  86096. this._colorShader._preBind();
  86097. var boundingBox = mesh._boundingInfo.boundingBox;
  86098. var min = boundingBox.minimum;
  86099. var max = boundingBox.maximum;
  86100. var diff = max.subtract(min);
  86101. var median = min.add(diff.scale(0.5));
  86102. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86103. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86104. .multiply(boundingBox.getWorldMatrix());
  86105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86106. engine.setDepthFunctionToLess();
  86107. this._scene.resetCachedMaterial();
  86108. this._colorShader.bind(worldMatrix);
  86109. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86110. this._colorShader.unbind();
  86111. engine.setDepthFunctionToLessOrEqual();
  86112. engine.setDepthWrite(true);
  86113. engine.setColorWrite(true);
  86114. };
  86115. BoundingBoxRenderer.prototype.dispose = function () {
  86116. if (!this._colorShader) {
  86117. return;
  86118. }
  86119. this.renderList.dispose();
  86120. this._colorShader.dispose();
  86121. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86122. if (buffer) {
  86123. buffer.dispose();
  86124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86125. }
  86126. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86127. };
  86128. return BoundingBoxRenderer;
  86129. }());
  86130. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86131. })(BABYLON || (BABYLON = {}));
  86132. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86133. var BABYLON;
  86134. (function (BABYLON) {
  86135. /**
  86136. * Renders a layer on top of an existing scene
  86137. */
  86138. var UtilityLayerRenderer = /** @class */ (function () {
  86139. /**
  86140. * Instantiates a UtilityLayerRenderer
  86141. * @param originalScene the original scene that will be rendered on top of
  86142. */
  86143. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86144. var _this = this;
  86145. this.originalScene = originalScene;
  86146. /**
  86147. * If the utility layer should automatically be rendered on top of existing scene
  86148. */
  86149. this.shouldRender = true;
  86150. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86151. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86152. originalScene.getEngine().scenes.pop();
  86153. // Render directly on top of existing scene without clearing
  86154. this.utilityLayerScene.autoClear = false;
  86155. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86156. if (_this.shouldRender) {
  86157. _this.render();
  86158. }
  86159. });
  86160. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86161. _this.dispose();
  86162. });
  86163. }
  86164. /**
  86165. * Renders the utility layers scene on top of the original scene
  86166. */
  86167. UtilityLayerRenderer.prototype.render = function () {
  86168. this._updateCamera();
  86169. this.utilityLayerScene.render(false);
  86170. };
  86171. /**
  86172. * Disposes of the renderer
  86173. */
  86174. UtilityLayerRenderer.prototype.dispose = function () {
  86175. if (this._afterRenderObserver) {
  86176. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86177. }
  86178. if (this._sceneDisposeObserver) {
  86179. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86180. }
  86181. this.utilityLayerScene.dispose();
  86182. };
  86183. UtilityLayerRenderer.prototype._updateCamera = function () {
  86184. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86185. };
  86186. return UtilityLayerRenderer;
  86187. }());
  86188. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86189. })(BABYLON || (BABYLON = {}));
  86190. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86191. var BABYLON;
  86192. (function (BABYLON) {
  86193. /**
  86194. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  86195. */
  86196. var Gizmo = /** @class */ (function () {
  86197. /**
  86198. * Creates a gizmo
  86199. * @param gizmoLayer The utility layer the gizmo will be added to
  86200. */
  86201. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  86202. var _this = this;
  86203. this.gizmoLayer = gizmoLayer;
  86204. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  86205. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  86206. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  86207. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 5;
  86208. _this._rootMesh.scaling.set(dist, dist, dist);
  86209. }
  86210. if (_this.attachedMesh) {
  86211. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  86212. }
  86213. });
  86214. }
  86215. /**
  86216. * Disposes of the gizmo
  86217. */
  86218. Gizmo.prototype.dispose = function () {
  86219. this._rootMesh.dispose();
  86220. if (this._beforeRenderObserver) {
  86221. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  86222. }
  86223. };
  86224. return Gizmo;
  86225. }());
  86226. BABYLON.Gizmo = Gizmo;
  86227. })(BABYLON || (BABYLON = {}));
  86228. //# sourceMappingURL=babylon.gizmo.js.map
  86229. var BABYLON;
  86230. (function (BABYLON) {
  86231. /**
  86232. * Single axis drag gizmo
  86233. */
  86234. var AxisDragGizmo = /** @class */ (function (_super) {
  86235. __extends(AxisDragGizmo, _super);
  86236. /**
  86237. * Creates an AxisDragGizmo
  86238. * @param gizmoLayer The utility layer the gizmo will be added to
  86239. * @param dragAxis The axis which the gizmo will be able to drag on
  86240. * @param color The color of the gizmo
  86241. */
  86242. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  86243. var _this = _super.call(this, gizmoLayer) || this;
  86244. // Create Material
  86245. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86246. coloredMaterial.disableLighting = true;
  86247. coloredMaterial.emissiveColor = color;
  86248. // Build mesh on root node
  86249. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86250. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86251. _this._rootMesh.addChild(arrowMesh);
  86252. _this._rootMesh.addChild(arrowTail);
  86253. // Position arrow pointing in its drag axis
  86254. arrowMesh.scaling.scaleInPlace(0.1);
  86255. arrowMesh.material = coloredMaterial;
  86256. arrowMesh.rotation.x = Math.PI / 2;
  86257. arrowMesh.position.z += 0.3;
  86258. arrowTail.rotation.x = Math.PI / 2;
  86259. arrowTail.material = coloredMaterial;
  86260. arrowTail.position.z += 0.2;
  86261. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86262. // Add drag behavior to handle events when the gizmo is dragged
  86263. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis, pointerObservableScene: gizmoLayer.originalScene });
  86264. _this._dragBehavior.moveAttached = false;
  86265. _this._rootMesh.addBehavior(_this._dragBehavior);
  86266. _this._dragBehavior.onDragObservable.add(function (event) {
  86267. if (_this.attachedMesh) {
  86268. _this.attachedMesh.position.addInPlace(event.delta);
  86269. }
  86270. });
  86271. return _this;
  86272. }
  86273. /**
  86274. * Disposes of the gizmo
  86275. */
  86276. AxisDragGizmo.prototype.dispose = function () {
  86277. this._dragBehavior.detach();
  86278. _super.prototype.dispose.call(this);
  86279. };
  86280. return AxisDragGizmo;
  86281. }(BABYLON.Gizmo));
  86282. BABYLON.AxisDragGizmo = AxisDragGizmo;
  86283. })(BABYLON || (BABYLON = {}));
  86284. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  86285. var BABYLON;
  86286. (function (BABYLON) {
  86287. /**
  86288. * Gizmo that enables dragging a mesh along 3 axis
  86289. */
  86290. var PositionGizmo = /** @class */ (function (_super) {
  86291. __extends(PositionGizmo, _super);
  86292. /**
  86293. * Creates a PositionGizmo
  86294. * @param gizmoLayer The utility layer the gizmo will be added to
  86295. */
  86296. function PositionGizmo(gizmoLayer) {
  86297. var _this = _super.call(this, gizmoLayer) || this;
  86298. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86299. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86300. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86301. return _this;
  86302. }
  86303. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  86304. set: function (mesh) {
  86305. this._xDrag.attachedMesh = mesh;
  86306. this._yDrag.attachedMesh = mesh;
  86307. this._zDrag.attachedMesh = mesh;
  86308. },
  86309. enumerable: true,
  86310. configurable: true
  86311. });
  86312. /**
  86313. * Disposes of the gizmo
  86314. */
  86315. PositionGizmo.prototype.dispose = function () {
  86316. this._xDrag.dispose();
  86317. this._yDrag.dispose();
  86318. this._zDrag.dispose();
  86319. };
  86320. return PositionGizmo;
  86321. }(BABYLON.Gizmo));
  86322. BABYLON.PositionGizmo = PositionGizmo;
  86323. })(BABYLON || (BABYLON = {}));
  86324. //# sourceMappingURL=babylon.positionGizmo.js.map
  86325. var BABYLON;
  86326. (function (BABYLON) {
  86327. /**
  86328. * Defines a target to use with MorphTargetManager
  86329. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86330. */
  86331. var MorphTarget = /** @class */ (function () {
  86332. /**
  86333. * Creates a new MorphTarget
  86334. * @param name defines the name of the target
  86335. * @param influence defines the influence to use
  86336. */
  86337. function MorphTarget(
  86338. /** defines the name of the target */
  86339. name, influence, scene) {
  86340. if (influence === void 0) { influence = 0; }
  86341. if (scene === void 0) { scene = null; }
  86342. this.name = name;
  86343. /**
  86344. * Gets or sets the list of animations
  86345. */
  86346. this.animations = new Array();
  86347. this._positions = null;
  86348. this._normals = null;
  86349. this._tangents = null;
  86350. /**
  86351. * Observable raised when the influence changes
  86352. */
  86353. this.onInfluenceChanged = new BABYLON.Observable();
  86354. this._animationPropertiesOverride = null;
  86355. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86356. this.influence = influence;
  86357. }
  86358. Object.defineProperty(MorphTarget.prototype, "influence", {
  86359. /**
  86360. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86361. */
  86362. get: function () {
  86363. return this._influence;
  86364. },
  86365. set: function (influence) {
  86366. if (this._influence === influence) {
  86367. return;
  86368. }
  86369. var previous = this._influence;
  86370. this._influence = influence;
  86371. if (this.onInfluenceChanged.hasObservers) {
  86372. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86373. }
  86374. },
  86375. enumerable: true,
  86376. configurable: true
  86377. });
  86378. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86379. /**
  86380. * Gets or sets the animation properties override
  86381. */
  86382. get: function () {
  86383. if (!this._animationPropertiesOverride && this._scene) {
  86384. return this._scene.animationPropertiesOverride;
  86385. }
  86386. return this._animationPropertiesOverride;
  86387. },
  86388. set: function (value) {
  86389. this._animationPropertiesOverride = value;
  86390. },
  86391. enumerable: true,
  86392. configurable: true
  86393. });
  86394. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86395. /**
  86396. * Gets a boolean defining if the target contains position data
  86397. */
  86398. get: function () {
  86399. return !!this._positions;
  86400. },
  86401. enumerable: true,
  86402. configurable: true
  86403. });
  86404. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86405. /**
  86406. * Gets a boolean defining if the target contains normal data
  86407. */
  86408. get: function () {
  86409. return !!this._normals;
  86410. },
  86411. enumerable: true,
  86412. configurable: true
  86413. });
  86414. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86415. /**
  86416. * Gets a boolean defining if the target contains tangent data
  86417. */
  86418. get: function () {
  86419. return !!this._tangents;
  86420. },
  86421. enumerable: true,
  86422. configurable: true
  86423. });
  86424. /**
  86425. * Affects position data to this target
  86426. * @param data defines the position data to use
  86427. */
  86428. MorphTarget.prototype.setPositions = function (data) {
  86429. this._positions = data;
  86430. };
  86431. /**
  86432. * Gets the position data stored in this target
  86433. * @returns a FloatArray containing the position data (or null if not present)
  86434. */
  86435. MorphTarget.prototype.getPositions = function () {
  86436. return this._positions;
  86437. };
  86438. /**
  86439. * Affects normal data to this target
  86440. * @param data defines the normal data to use
  86441. */
  86442. MorphTarget.prototype.setNormals = function (data) {
  86443. this._normals = data;
  86444. };
  86445. /**
  86446. * Gets the normal data stored in this target
  86447. * @returns a FloatArray containing the normal data (or null if not present)
  86448. */
  86449. MorphTarget.prototype.getNormals = function () {
  86450. return this._normals;
  86451. };
  86452. /**
  86453. * Affects tangent data to this target
  86454. * @param data defines the tangent data to use
  86455. */
  86456. MorphTarget.prototype.setTangents = function (data) {
  86457. this._tangents = data;
  86458. };
  86459. /**
  86460. * Gets the tangent data stored in this target
  86461. * @returns a FloatArray containing the tangent data (or null if not present)
  86462. */
  86463. MorphTarget.prototype.getTangents = function () {
  86464. return this._tangents;
  86465. };
  86466. /**
  86467. * Serializes the current target into a Serialization object
  86468. * @returns the serialized object
  86469. */
  86470. MorphTarget.prototype.serialize = function () {
  86471. var serializationObject = {};
  86472. serializationObject.name = this.name;
  86473. serializationObject.influence = this.influence;
  86474. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86475. if (this.hasNormals) {
  86476. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86477. }
  86478. if (this.hasTangents) {
  86479. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86480. }
  86481. // Animations
  86482. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86483. return serializationObject;
  86484. };
  86485. // Statics
  86486. /**
  86487. * Creates a new target from serialized data
  86488. * @param serializationObject defines the serialized data to use
  86489. * @returns a new MorphTarget
  86490. */
  86491. MorphTarget.Parse = function (serializationObject) {
  86492. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86493. result.setPositions(serializationObject.positions);
  86494. if (serializationObject.normals) {
  86495. result.setNormals(serializationObject.normals);
  86496. }
  86497. if (serializationObject.tangents) {
  86498. result.setTangents(serializationObject.tangents);
  86499. }
  86500. // Animations
  86501. if (serializationObject.animations) {
  86502. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86503. var parsedAnimation = serializationObject.animations[animationIndex];
  86504. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86505. }
  86506. }
  86507. return result;
  86508. };
  86509. /**
  86510. * Creates a MorphTarget from mesh data
  86511. * @param mesh defines the source mesh
  86512. * @param name defines the name to use for the new target
  86513. * @param influence defines the influence to attach to the target
  86514. * @returns a new MorphTarget
  86515. */
  86516. MorphTarget.FromMesh = function (mesh, name, influence) {
  86517. if (!name) {
  86518. name = mesh.name;
  86519. }
  86520. var result = new MorphTarget(name, influence, mesh.getScene());
  86521. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86522. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86523. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86524. }
  86525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86526. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86527. }
  86528. return result;
  86529. };
  86530. return MorphTarget;
  86531. }());
  86532. BABYLON.MorphTarget = MorphTarget;
  86533. })(BABYLON || (BABYLON = {}));
  86534. //# sourceMappingURL=babylon.morphTarget.js.map
  86535. var BABYLON;
  86536. (function (BABYLON) {
  86537. /**
  86538. * This class is used to deform meshes using morphing between different targets
  86539. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86540. */
  86541. var MorphTargetManager = /** @class */ (function () {
  86542. /**
  86543. * Creates a new MorphTargetManager
  86544. * @param scene defines the current scene
  86545. */
  86546. function MorphTargetManager(scene) {
  86547. if (scene === void 0) { scene = null; }
  86548. this._targets = new Array();
  86549. this._targetObservable = new Array();
  86550. this._activeTargets = new BABYLON.SmartArray(16);
  86551. this._supportsNormals = false;
  86552. this._supportsTangents = false;
  86553. this._vertexCount = 0;
  86554. this._uniqueId = 0;
  86555. this._tempInfluences = new Array();
  86556. if (!scene) {
  86557. scene = BABYLON.Engine.LastCreatedScene;
  86558. }
  86559. this._scene = scene;
  86560. if (this._scene) {
  86561. this._scene.morphTargetManagers.push(this);
  86562. this._uniqueId = this._scene.getUniqueId();
  86563. }
  86564. }
  86565. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86566. /**
  86567. * Gets the unique ID of this manager
  86568. */
  86569. get: function () {
  86570. return this._uniqueId;
  86571. },
  86572. enumerable: true,
  86573. configurable: true
  86574. });
  86575. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86576. /**
  86577. * Gets the number of vertices handled by this manager
  86578. */
  86579. get: function () {
  86580. return this._vertexCount;
  86581. },
  86582. enumerable: true,
  86583. configurable: true
  86584. });
  86585. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86586. /**
  86587. * Gets a boolean indicating if this manager supports morphing of normals
  86588. */
  86589. get: function () {
  86590. return this._supportsNormals;
  86591. },
  86592. enumerable: true,
  86593. configurable: true
  86594. });
  86595. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86596. /**
  86597. * Gets a boolean indicating if this manager supports morphing of tangents
  86598. */
  86599. get: function () {
  86600. return this._supportsTangents;
  86601. },
  86602. enumerable: true,
  86603. configurable: true
  86604. });
  86605. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86606. /**
  86607. * Gets the number of targets stored in this manager
  86608. */
  86609. get: function () {
  86610. return this._targets.length;
  86611. },
  86612. enumerable: true,
  86613. configurable: true
  86614. });
  86615. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86616. /**
  86617. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86618. */
  86619. get: function () {
  86620. return this._activeTargets.length;
  86621. },
  86622. enumerable: true,
  86623. configurable: true
  86624. });
  86625. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86626. /**
  86627. * Gets the list of influences (one per target)
  86628. */
  86629. get: function () {
  86630. return this._influences;
  86631. },
  86632. enumerable: true,
  86633. configurable: true
  86634. });
  86635. /**
  86636. * Gets the active target at specified index. An active target is a target with an influence > 0
  86637. * @param index defines the index to check
  86638. * @returns the requested target
  86639. */
  86640. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86641. return this._activeTargets.data[index];
  86642. };
  86643. /**
  86644. * Gets the target at specified index
  86645. * @param index defines the index to check
  86646. * @returns the requested target
  86647. */
  86648. MorphTargetManager.prototype.getTarget = function (index) {
  86649. return this._targets[index];
  86650. };
  86651. /**
  86652. * Add a new target to this manager
  86653. * @param target defines the target to add
  86654. */
  86655. MorphTargetManager.prototype.addTarget = function (target) {
  86656. var _this = this;
  86657. this._targets.push(target);
  86658. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86659. _this._syncActiveTargets(needUpdate);
  86660. }));
  86661. this._syncActiveTargets(true);
  86662. };
  86663. /**
  86664. * Removes a target from the manager
  86665. * @param target defines the target to remove
  86666. */
  86667. MorphTargetManager.prototype.removeTarget = function (target) {
  86668. var index = this._targets.indexOf(target);
  86669. if (index >= 0) {
  86670. this._targets.splice(index, 1);
  86671. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86672. this._syncActiveTargets(true);
  86673. }
  86674. };
  86675. /**
  86676. * Serializes the current manager into a Serialization object
  86677. * @returns the serialized object
  86678. */
  86679. MorphTargetManager.prototype.serialize = function () {
  86680. var serializationObject = {};
  86681. serializationObject.id = this.uniqueId;
  86682. serializationObject.targets = [];
  86683. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86684. var target = _a[_i];
  86685. serializationObject.targets.push(target.serialize());
  86686. }
  86687. return serializationObject;
  86688. };
  86689. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86690. var influenceCount = 0;
  86691. this._activeTargets.reset();
  86692. this._supportsNormals = true;
  86693. this._supportsTangents = true;
  86694. this._vertexCount = 0;
  86695. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86696. var target = _a[_i];
  86697. this._activeTargets.push(target);
  86698. this._tempInfluences[influenceCount++] = target.influence;
  86699. var positions = target.getPositions();
  86700. if (positions) {
  86701. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86702. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86703. var vertexCount = positions.length / 3;
  86704. if (this._vertexCount === 0) {
  86705. this._vertexCount = vertexCount;
  86706. }
  86707. else if (this._vertexCount !== vertexCount) {
  86708. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86709. return;
  86710. }
  86711. }
  86712. }
  86713. if (!this._influences || this._influences.length !== influenceCount) {
  86714. this._influences = new Float32Array(influenceCount);
  86715. }
  86716. for (var index = 0; index < influenceCount; index++) {
  86717. this._influences[index] = this._tempInfluences[index];
  86718. }
  86719. if (needUpdate) {
  86720. this.synchronize();
  86721. }
  86722. };
  86723. /**
  86724. * Syncrhonize the targets with all the meshes using this morph target manager
  86725. */
  86726. MorphTargetManager.prototype.synchronize = function () {
  86727. if (!this._scene) {
  86728. return;
  86729. }
  86730. // Flag meshes as dirty to resync with the active targets
  86731. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86732. var mesh = _a[_i];
  86733. if (mesh.morphTargetManager === this) {
  86734. mesh._syncGeometryWithMorphTargetManager();
  86735. }
  86736. }
  86737. };
  86738. // Statics
  86739. /**
  86740. * Creates a new MorphTargetManager from serialized data
  86741. * @param serializationObject defines the serialized data
  86742. * @param scene defines the hosting scene
  86743. * @returns the new MorphTargetManager
  86744. */
  86745. MorphTargetManager.Parse = function (serializationObject, scene) {
  86746. var result = new MorphTargetManager(scene);
  86747. result._uniqueId = serializationObject.id;
  86748. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86749. var targetData = _a[_i];
  86750. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86751. }
  86752. return result;
  86753. };
  86754. return MorphTargetManager;
  86755. }());
  86756. BABYLON.MorphTargetManager = MorphTargetManager;
  86757. })(BABYLON || (BABYLON = {}));
  86758. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86759. var BABYLON;
  86760. (function (BABYLON) {
  86761. var Octree = /** @class */ (function () {
  86762. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86763. if (maxDepth === void 0) { maxDepth = 2; }
  86764. this.maxDepth = maxDepth;
  86765. this.dynamicContent = new Array();
  86766. this._maxBlockCapacity = maxBlockCapacity || 64;
  86767. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86768. this._creationFunc = creationFunc;
  86769. }
  86770. // Methods
  86771. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86772. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86773. };
  86774. Octree.prototype.addMesh = function (entry) {
  86775. for (var index = 0; index < this.blocks.length; index++) {
  86776. var block = this.blocks[index];
  86777. block.addEntry(entry);
  86778. }
  86779. };
  86780. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86781. this._selectionContent.reset();
  86782. for (var index = 0; index < this.blocks.length; index++) {
  86783. var block = this.blocks[index];
  86784. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86785. }
  86786. if (allowDuplicate) {
  86787. this._selectionContent.concat(this.dynamicContent);
  86788. }
  86789. else {
  86790. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86791. }
  86792. return this._selectionContent;
  86793. };
  86794. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86795. this._selectionContent.reset();
  86796. for (var index = 0; index < this.blocks.length; index++) {
  86797. var block = this.blocks[index];
  86798. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86799. }
  86800. if (allowDuplicate) {
  86801. this._selectionContent.concat(this.dynamicContent);
  86802. }
  86803. else {
  86804. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86805. }
  86806. return this._selectionContent;
  86807. };
  86808. Octree.prototype.intersectsRay = function (ray) {
  86809. this._selectionContent.reset();
  86810. for (var index = 0; index < this.blocks.length; index++) {
  86811. var block = this.blocks[index];
  86812. block.intersectsRay(ray, this._selectionContent);
  86813. }
  86814. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86815. return this._selectionContent;
  86816. };
  86817. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86818. target.blocks = new Array();
  86819. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86820. // Segmenting space
  86821. for (var x = 0; x < 2; x++) {
  86822. for (var y = 0; y < 2; y++) {
  86823. for (var z = 0; z < 2; z++) {
  86824. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86825. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86826. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86827. block.addEntries(entries);
  86828. target.blocks.push(block);
  86829. }
  86830. }
  86831. }
  86832. };
  86833. Octree.CreationFuncForMeshes = function (entry, block) {
  86834. var boundingInfo = entry.getBoundingInfo();
  86835. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86836. block.entries.push(entry);
  86837. }
  86838. };
  86839. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86840. var boundingInfo = entry.getBoundingInfo();
  86841. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86842. block.entries.push(entry);
  86843. }
  86844. };
  86845. return Octree;
  86846. }());
  86847. BABYLON.Octree = Octree;
  86848. })(BABYLON || (BABYLON = {}));
  86849. //# sourceMappingURL=babylon.octree.js.map
  86850. var BABYLON;
  86851. (function (BABYLON) {
  86852. var OctreeBlock = /** @class */ (function () {
  86853. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86854. this.entries = new Array();
  86855. this._boundingVectors = new Array();
  86856. this._capacity = capacity;
  86857. this._depth = depth;
  86858. this._maxDepth = maxDepth;
  86859. this._creationFunc = creationFunc;
  86860. this._minPoint = minPoint;
  86861. this._maxPoint = maxPoint;
  86862. this._boundingVectors.push(minPoint.clone());
  86863. this._boundingVectors.push(maxPoint.clone());
  86864. this._boundingVectors.push(minPoint.clone());
  86865. this._boundingVectors[2].x = maxPoint.x;
  86866. this._boundingVectors.push(minPoint.clone());
  86867. this._boundingVectors[3].y = maxPoint.y;
  86868. this._boundingVectors.push(minPoint.clone());
  86869. this._boundingVectors[4].z = maxPoint.z;
  86870. this._boundingVectors.push(maxPoint.clone());
  86871. this._boundingVectors[5].z = minPoint.z;
  86872. this._boundingVectors.push(maxPoint.clone());
  86873. this._boundingVectors[6].x = minPoint.x;
  86874. this._boundingVectors.push(maxPoint.clone());
  86875. this._boundingVectors[7].y = minPoint.y;
  86876. }
  86877. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86878. // Property
  86879. get: function () {
  86880. return this._capacity;
  86881. },
  86882. enumerable: true,
  86883. configurable: true
  86884. });
  86885. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86886. get: function () {
  86887. return this._minPoint;
  86888. },
  86889. enumerable: true,
  86890. configurable: true
  86891. });
  86892. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86893. get: function () {
  86894. return this._maxPoint;
  86895. },
  86896. enumerable: true,
  86897. configurable: true
  86898. });
  86899. // Methods
  86900. OctreeBlock.prototype.addEntry = function (entry) {
  86901. if (this.blocks) {
  86902. for (var index = 0; index < this.blocks.length; index++) {
  86903. var block = this.blocks[index];
  86904. block.addEntry(entry);
  86905. }
  86906. return;
  86907. }
  86908. this._creationFunc(entry, this);
  86909. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86910. this.createInnerBlocks();
  86911. }
  86912. };
  86913. OctreeBlock.prototype.addEntries = function (entries) {
  86914. for (var index = 0; index < entries.length; index++) {
  86915. var mesh = entries[index];
  86916. this.addEntry(mesh);
  86917. }
  86918. };
  86919. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86920. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86921. if (this.blocks) {
  86922. for (var index = 0; index < this.blocks.length; index++) {
  86923. var block = this.blocks[index];
  86924. block.select(frustumPlanes, selection, allowDuplicate);
  86925. }
  86926. return;
  86927. }
  86928. if (allowDuplicate) {
  86929. selection.concat(this.entries);
  86930. }
  86931. else {
  86932. selection.concatWithNoDuplicate(this.entries);
  86933. }
  86934. }
  86935. };
  86936. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86937. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86938. if (this.blocks) {
  86939. for (var index = 0; index < this.blocks.length; index++) {
  86940. var block = this.blocks[index];
  86941. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86942. }
  86943. return;
  86944. }
  86945. if (allowDuplicate) {
  86946. selection.concat(this.entries);
  86947. }
  86948. else {
  86949. selection.concatWithNoDuplicate(this.entries);
  86950. }
  86951. }
  86952. };
  86953. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86954. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86955. if (this.blocks) {
  86956. for (var index = 0; index < this.blocks.length; index++) {
  86957. var block = this.blocks[index];
  86958. block.intersectsRay(ray, selection);
  86959. }
  86960. return;
  86961. }
  86962. selection.concatWithNoDuplicate(this.entries);
  86963. }
  86964. };
  86965. OctreeBlock.prototype.createInnerBlocks = function () {
  86966. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86967. };
  86968. return OctreeBlock;
  86969. }());
  86970. BABYLON.OctreeBlock = OctreeBlock;
  86971. })(BABYLON || (BABYLON = {}));
  86972. //# sourceMappingURL=babylon.octreeBlock.js.map
  86973. var BABYLON;
  86974. (function (BABYLON) {
  86975. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86976. __extends(VRDistortionCorrectionPostProcess, _super);
  86977. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86978. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86979. 'LensCenter',
  86980. 'Scale',
  86981. 'ScaleIn',
  86982. 'HmdWarpParam'
  86983. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86984. _this._isRightEye = isRightEye;
  86985. _this._distortionFactors = vrMetrics.distortionK;
  86986. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86987. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86988. _this.adaptScaleToCurrentViewport = true;
  86989. _this.onSizeChangedObservable.add(function () {
  86990. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86991. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86992. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86993. });
  86994. _this.onApplyObservable.add(function (effect) {
  86995. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86996. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86997. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86998. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86999. });
  87000. return _this;
  87001. }
  87002. return VRDistortionCorrectionPostProcess;
  87003. }(BABYLON.PostProcess));
  87004. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  87005. })(BABYLON || (BABYLON = {}));
  87006. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  87007. var BABYLON;
  87008. (function (BABYLON) {
  87009. /**
  87010. * Postprocess used to generate anaglyphic rendering
  87011. */
  87012. var AnaglyphPostProcess = /** @class */ (function (_super) {
  87013. __extends(AnaglyphPostProcess, _super);
  87014. /**
  87015. * Creates a new AnaglyphPostProcess
  87016. * @param name defines postprocess name
  87017. * @param options defines creation options or target ratio scale
  87018. * @param rigCameras defines cameras using this postprocess
  87019. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  87020. * @param engine defines hosting engine
  87021. * @param reusable defines if the postprocess will be reused multiple times per frame
  87022. */
  87023. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  87024. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  87025. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87026. _this.onApplyObservable.add(function (effect) {
  87027. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  87028. });
  87029. return _this;
  87030. }
  87031. return AnaglyphPostProcess;
  87032. }(BABYLON.PostProcess));
  87033. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  87034. })(BABYLON || (BABYLON = {}));
  87035. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  87036. var BABYLON;
  87037. (function (BABYLON) {
  87038. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  87039. __extends(StereoscopicInterlacePostProcess, _super);
  87040. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  87041. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  87042. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87043. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87044. _this.onSizeChangedObservable.add(function () {
  87045. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87046. });
  87047. _this.onApplyObservable.add(function (effect) {
  87048. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  87049. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  87050. });
  87051. return _this;
  87052. }
  87053. return StereoscopicInterlacePostProcess;
  87054. }(BABYLON.PostProcess));
  87055. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  87056. })(BABYLON || (BABYLON = {}));
  87057. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  87058. var BABYLON;
  87059. (function (BABYLON) {
  87060. /**
  87061. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  87062. * Screen rotation is taken into account.
  87063. */
  87064. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  87065. function FreeCameraDeviceOrientationInput() {
  87066. var _this = this;
  87067. this._screenOrientationAngle = 0;
  87068. this._screenQuaternion = new BABYLON.Quaternion();
  87069. this._alpha = 0;
  87070. this._beta = 0;
  87071. this._gamma = 0;
  87072. this._orientationChanged = function () {
  87073. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  87074. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  87075. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  87076. };
  87077. this._deviceOrientation = function (evt) {
  87078. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  87079. _this._beta = evt.beta !== null ? evt.beta : 0;
  87080. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  87081. };
  87082. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  87083. this._orientationChanged();
  87084. }
  87085. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  87086. get: function () {
  87087. return this._camera;
  87088. },
  87089. set: function (camera) {
  87090. this._camera = camera;
  87091. if (this._camera != null && !this._camera.rotationQuaternion) {
  87092. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  87093. }
  87094. },
  87095. enumerable: true,
  87096. configurable: true
  87097. });
  87098. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87099. window.addEventListener("orientationchange", this._orientationChanged);
  87100. window.addEventListener("deviceorientation", this._deviceOrientation);
  87101. //In certain cases, the attach control is called AFTER orientation was changed,
  87102. //So this is needed.
  87103. this._orientationChanged();
  87104. };
  87105. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  87106. window.removeEventListener("orientationchange", this._orientationChanged);
  87107. window.removeEventListener("deviceorientation", this._deviceOrientation);
  87108. };
  87109. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  87110. //if no device orientation provided, don't update the rotation.
  87111. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  87112. if (!this._alpha)
  87113. return;
  87114. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  87115. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  87116. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  87117. //Mirror on XY Plane
  87118. this._camera.rotationQuaternion.z *= -1;
  87119. this._camera.rotationQuaternion.w *= -1;
  87120. };
  87121. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  87122. return "FreeCameraDeviceOrientationInput";
  87123. };
  87124. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  87125. return "deviceOrientation";
  87126. };
  87127. return FreeCameraDeviceOrientationInput;
  87128. }());
  87129. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  87130. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  87131. })(BABYLON || (BABYLON = {}));
  87132. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  87133. var BABYLON;
  87134. (function (BABYLON) {
  87135. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  87136. function ArcRotateCameraVRDeviceOrientationInput() {
  87137. this.alphaCorrection = 1;
  87138. this.betaCorrection = 1;
  87139. this.gammaCorrection = 1;
  87140. this._alpha = 0;
  87141. this._gamma = 0;
  87142. this._dirty = false;
  87143. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  87144. }
  87145. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87146. this.camera.attachControl(element, noPreventDefault);
  87147. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  87148. };
  87149. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  87150. if (evt.alpha !== null) {
  87151. this._alpha = +evt.alpha | 0;
  87152. }
  87153. if (evt.gamma !== null) {
  87154. this._gamma = +evt.gamma | 0;
  87155. }
  87156. this._dirty = true;
  87157. };
  87158. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  87159. if (this._dirty) {
  87160. this._dirty = false;
  87161. if (this._gamma < 0) {
  87162. this._gamma = 180 + this._gamma;
  87163. }
  87164. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  87165. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  87166. }
  87167. };
  87168. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  87169. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  87170. };
  87171. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  87172. return "ArcRotateCameraVRDeviceOrientationInput";
  87173. };
  87174. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  87175. return "VRDeviceOrientation";
  87176. };
  87177. return ArcRotateCameraVRDeviceOrientationInput;
  87178. }());
  87179. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  87180. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  87181. })(BABYLON || (BABYLON = {}));
  87182. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  87183. var BABYLON;
  87184. (function (BABYLON) {
  87185. var VRCameraMetrics = /** @class */ (function () {
  87186. function VRCameraMetrics() {
  87187. this.compensateDistortion = true;
  87188. }
  87189. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  87190. get: function () {
  87191. return this.hResolution / (2 * this.vResolution);
  87192. },
  87193. enumerable: true,
  87194. configurable: true
  87195. });
  87196. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  87197. get: function () {
  87198. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  87199. },
  87200. enumerable: true,
  87201. configurable: true
  87202. });
  87203. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  87204. get: function () {
  87205. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87206. var h = (4 * meters) / this.hScreenSize;
  87207. return BABYLON.Matrix.Translation(h, 0, 0);
  87208. },
  87209. enumerable: true,
  87210. configurable: true
  87211. });
  87212. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  87213. get: function () {
  87214. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87215. var h = (4 * meters) / this.hScreenSize;
  87216. return BABYLON.Matrix.Translation(-h, 0, 0);
  87217. },
  87218. enumerable: true,
  87219. configurable: true
  87220. });
  87221. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  87222. get: function () {
  87223. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  87224. },
  87225. enumerable: true,
  87226. configurable: true
  87227. });
  87228. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  87229. get: function () {
  87230. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  87231. },
  87232. enumerable: true,
  87233. configurable: true
  87234. });
  87235. VRCameraMetrics.GetDefault = function () {
  87236. var result = new VRCameraMetrics();
  87237. result.hResolution = 1280;
  87238. result.vResolution = 800;
  87239. result.hScreenSize = 0.149759993;
  87240. result.vScreenSize = 0.0935999975;
  87241. result.vScreenCenter = 0.0467999987;
  87242. result.eyeToScreenDistance = 0.0410000011;
  87243. result.lensSeparationDistance = 0.0635000020;
  87244. result.interpupillaryDistance = 0.0640000030;
  87245. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  87246. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  87247. result.postProcessScaleFactor = 1.714605507808412;
  87248. result.lensCenterOffset = 0.151976421;
  87249. return result;
  87250. };
  87251. return VRCameraMetrics;
  87252. }());
  87253. BABYLON.VRCameraMetrics = VRCameraMetrics;
  87254. })(BABYLON || (BABYLON = {}));
  87255. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  87256. var BABYLON;
  87257. (function (BABYLON) {
  87258. /**
  87259. * This represents a WebVR camera.
  87260. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  87261. * @example http://doc.babylonjs.com/how_to/webvr_camera
  87262. */
  87263. var WebVRFreeCamera = /** @class */ (function (_super) {
  87264. __extends(WebVRFreeCamera, _super);
  87265. /**
  87266. * Instantiates a WebVRFreeCamera.
  87267. * @param name The name of the WebVRFreeCamera
  87268. * @param position The starting anchor position for the camera
  87269. * @param scene The scene the camera belongs to
  87270. * @param webVROptions a set of customizable options for the webVRCamera
  87271. */
  87272. function WebVRFreeCamera(name, position, scene, webVROptions) {
  87273. if (webVROptions === void 0) { webVROptions = {}; }
  87274. var _this = _super.call(this, name, position, scene) || this;
  87275. _this.webVROptions = webVROptions;
  87276. /**
  87277. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  87278. */
  87279. _this._vrDevice = null;
  87280. /**
  87281. * The rawPose of the vrDevice.
  87282. */
  87283. _this.rawPose = null;
  87284. _this._specsVersion = "1.1";
  87285. _this._attached = false;
  87286. _this._descendants = [];
  87287. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  87288. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  87289. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  87290. _this._standingMatrix = null;
  87291. /**
  87292. * Represents device position in babylon space.
  87293. */
  87294. _this.devicePosition = BABYLON.Vector3.Zero();
  87295. /**
  87296. * Represents device rotation in babylon space.
  87297. */
  87298. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  87299. /**
  87300. * The scale of the device to be used when translating from device space to babylon space.
  87301. */
  87302. _this.deviceScaleFactor = 1;
  87303. _this._deviceToWorld = BABYLON.Matrix.Identity();
  87304. _this._worldToDevice = BABYLON.Matrix.Identity();
  87305. /**
  87306. * References to the webVR controllers for the vrDevice.
  87307. */
  87308. _this.controllers = [];
  87309. /**
  87310. * Emits an event when a controller is attached.
  87311. */
  87312. _this.onControllersAttachedObservable = new BABYLON.Observable();
  87313. /**
  87314. * Emits an event when a controller's mesh has been loaded;
  87315. */
  87316. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87317. /**
  87318. * If the rig cameras be used as parent instead of this camera.
  87319. */
  87320. _this.rigParenting = true;
  87321. _this._defaultHeight = undefined;
  87322. _this._workingVector = BABYLON.Vector3.Zero();
  87323. _this._oneVector = BABYLON.Vector3.One();
  87324. _this._workingMatrix = BABYLON.Matrix.Identity();
  87325. _this._cache.position = BABYLON.Vector3.Zero();
  87326. if (webVROptions.defaultHeight) {
  87327. _this._defaultHeight = webVROptions.defaultHeight;
  87328. _this.position.y = _this._defaultHeight;
  87329. }
  87330. _this.minZ = 0.1;
  87331. //legacy support - the compensation boolean was removed.
  87332. if (arguments.length === 5) {
  87333. _this.webVROptions = arguments[4];
  87334. }
  87335. // default webVR options
  87336. if (_this.webVROptions.trackPosition == undefined) {
  87337. _this.webVROptions.trackPosition = true;
  87338. }
  87339. if (_this.webVROptions.controllerMeshes == undefined) {
  87340. _this.webVROptions.controllerMeshes = true;
  87341. }
  87342. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  87343. _this.webVROptions.defaultLightingOnControllers = true;
  87344. }
  87345. _this.rotationQuaternion = new BABYLON.Quaternion();
  87346. if (_this.webVROptions && _this.webVROptions.positionScale) {
  87347. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  87348. }
  87349. //enable VR
  87350. var engine = _this.getEngine();
  87351. _this._onVREnabled = function (success) { if (success) {
  87352. _this.initControllers();
  87353. } };
  87354. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  87355. engine.initWebVR().add(function (event) {
  87356. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  87357. return;
  87358. }
  87359. _this._vrDevice = event.vrDisplay;
  87360. //reset the rig parameters.
  87361. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87362. if (_this._attached) {
  87363. _this.getEngine().enableVR();
  87364. }
  87365. });
  87366. if (typeof (VRFrameData) !== "undefined")
  87367. _this._frameData = new VRFrameData();
  87368. /**
  87369. * The idea behind the following lines:
  87370. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87371. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87372. * the second will not show it correctly.
  87373. *
  87374. * To solve this - each object that has the camera as parent will be added to a protected array.
  87375. * When the rig camera renders, it will take this array and set all of those to be its children.
  87376. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87377. * Amazing!
  87378. */
  87379. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87380. if (camera.parent === _this && _this.rigParenting) {
  87381. _this._descendants = _this.getDescendants(true, function (n) {
  87382. // don't take the cameras or the controllers!
  87383. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87384. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87385. return !isController && !isRigCamera;
  87386. });
  87387. _this._descendants.forEach(function (node) {
  87388. node.parent = camera;
  87389. });
  87390. }
  87391. });
  87392. scene.onAfterCameraRenderObservable.add(function (camera) {
  87393. if (camera.parent === _this && _this.rigParenting) {
  87394. _this._descendants.forEach(function (node) {
  87395. node.parent = _this;
  87396. });
  87397. }
  87398. });
  87399. return _this;
  87400. }
  87401. /**
  87402. * Gets the device distance from the ground in meters.
  87403. * @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.
  87404. */
  87405. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87406. if (this._standingMatrix) {
  87407. // Add standing matrix offset to get real offset from ground in room
  87408. this._standingMatrix.getTranslationToRef(this._workingVector);
  87409. return this._deviceRoomPosition.y + this._workingVector.y;
  87410. }
  87411. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87412. return this._defaultHeight || 0;
  87413. };
  87414. /**
  87415. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87416. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87417. */
  87418. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87419. var _this = this;
  87420. if (callback === void 0) { callback = function (bool) { }; }
  87421. // Use standing matrix if available
  87422. this.getEngine().initWebVRAsync().then(function (result) {
  87423. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87424. callback(false);
  87425. }
  87426. else {
  87427. _this._standingMatrix = new BABYLON.Matrix();
  87428. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87429. if (!_this.getScene().useRightHandedSystem) {
  87430. [2, 6, 8, 9, 14].forEach(function (num) {
  87431. if (_this._standingMatrix) {
  87432. _this._standingMatrix.m[num] *= -1;
  87433. }
  87434. });
  87435. }
  87436. callback(true);
  87437. }
  87438. });
  87439. };
  87440. /**
  87441. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87442. * @returns A promise with a boolean set to if the standing matrix is supported.
  87443. */
  87444. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87445. var _this = this;
  87446. return new Promise(function (res, rej) {
  87447. _this.useStandingMatrix(function (supported) {
  87448. res(supported);
  87449. });
  87450. });
  87451. };
  87452. /**
  87453. * Disposes the camera
  87454. */
  87455. WebVRFreeCamera.prototype.dispose = function () {
  87456. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87457. _super.prototype.dispose.call(this);
  87458. };
  87459. /**
  87460. * Gets a vrController by name.
  87461. * @param name The name of the controller to retreive
  87462. * @returns the controller matching the name specified or null if not found
  87463. */
  87464. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87465. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87466. var gp = _a[_i];
  87467. if (gp.hand === name) {
  87468. return gp;
  87469. }
  87470. }
  87471. return null;
  87472. };
  87473. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87474. /**
  87475. * The controller corrisponding to the users left hand.
  87476. */
  87477. get: function () {
  87478. if (!this._leftController) {
  87479. this._leftController = this.getControllerByName("left");
  87480. }
  87481. return this._leftController;
  87482. },
  87483. enumerable: true,
  87484. configurable: true
  87485. });
  87486. ;
  87487. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87488. /**
  87489. * The controller corrisponding to the users right hand.
  87490. */
  87491. get: function () {
  87492. if (!this._rightController) {
  87493. this._rightController = this.getControllerByName("right");
  87494. }
  87495. return this._rightController;
  87496. },
  87497. enumerable: true,
  87498. configurable: true
  87499. });
  87500. ;
  87501. /**
  87502. * Casts a ray forward from the vrCamera's gaze.
  87503. * @param length Length of the ray (default: 100)
  87504. * @returns the ray corrisponding to the gaze
  87505. */
  87506. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87507. if (length === void 0) { length = 100; }
  87508. if (this.leftCamera) {
  87509. // Use left eye to avoid computation to compute center on every call
  87510. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87511. }
  87512. else {
  87513. return _super.prototype.getForwardRay.call(this, length);
  87514. }
  87515. };
  87516. /**
  87517. * Updates the camera based on device's frame data
  87518. */
  87519. WebVRFreeCamera.prototype._checkInputs = function () {
  87520. if (this._vrDevice && this._vrDevice.isPresenting) {
  87521. this._vrDevice.getFrameData(this._frameData);
  87522. this.updateFromDevice(this._frameData.pose);
  87523. }
  87524. _super.prototype._checkInputs.call(this);
  87525. };
  87526. /**
  87527. * Updates the poseControlled values based on the input device pose.
  87528. * @param poseData Pose coming from the device
  87529. */
  87530. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87531. if (poseData && poseData.orientation) {
  87532. this.rawPose = poseData;
  87533. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87534. if (this.getScene().useRightHandedSystem) {
  87535. this._deviceRoomRotationQuaternion.z *= -1;
  87536. this._deviceRoomRotationQuaternion.w *= -1;
  87537. }
  87538. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87539. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87540. if (this.getScene().useRightHandedSystem) {
  87541. this._deviceRoomPosition.z *= -1;
  87542. }
  87543. }
  87544. }
  87545. };
  87546. /**
  87547. * WebVR's attach control will start broadcasting frames to the device.
  87548. * Note that in certain browsers (chrome for example) this function must be called
  87549. * within a user-interaction callback. Example:
  87550. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87551. *
  87552. * @param element html element to attach the vrDevice to
  87553. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87554. */
  87555. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87556. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87557. this._attached = true;
  87558. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87559. if (this._vrDevice) {
  87560. this.getEngine().enableVR();
  87561. }
  87562. };
  87563. /**
  87564. * Detaches the camera from the html element and disables VR
  87565. *
  87566. * @param element html element to detach from
  87567. */
  87568. WebVRFreeCamera.prototype.detachControl = function (element) {
  87569. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87570. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87571. _super.prototype.detachControl.call(this, element);
  87572. this._attached = false;
  87573. this.getEngine().disableVR();
  87574. };
  87575. /**
  87576. * @returns the name of this class
  87577. */
  87578. WebVRFreeCamera.prototype.getClassName = function () {
  87579. return "WebVRFreeCamera";
  87580. };
  87581. /**
  87582. * Calls resetPose on the vrDisplay
  87583. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87584. */
  87585. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87586. //uses the vrDisplay's "resetPose()".
  87587. //pitch and roll won't be affected.
  87588. this._vrDevice.resetPose();
  87589. };
  87590. /**
  87591. * Updates the rig cameras (left and right eye)
  87592. */
  87593. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87594. var camLeft = this._rigCameras[0];
  87595. var camRight = this._rigCameras[1];
  87596. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87597. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87598. camLeft.position.copyFrom(this._deviceRoomPosition);
  87599. camRight.position.copyFrom(this._deviceRoomPosition);
  87600. };
  87601. /**
  87602. * Updates the cached values of the camera
  87603. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87604. */
  87605. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87606. var _this = this;
  87607. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87608. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87609. if (!this.updateCacheCalled) {
  87610. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87611. this.updateCacheCalled = true;
  87612. this.update();
  87613. }
  87614. // Set working vector to the device position in room space rotated by the new rotation
  87615. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87616. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87617. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87618. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87619. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87620. // Add translation from anchor position
  87621. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87622. this._workingVector.addInPlace(this.position);
  87623. this._workingVector.subtractInPlace(this._cache.position);
  87624. this._deviceToWorld.setTranslation(this._workingVector);
  87625. // Set an inverted matrix to be used when updating the camera
  87626. this._deviceToWorld.invertToRef(this._worldToDevice);
  87627. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87628. this.controllers.forEach(function (controller) {
  87629. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87630. controller.update();
  87631. });
  87632. }
  87633. if (!ignoreParentClass) {
  87634. _super.prototype._updateCache.call(this);
  87635. }
  87636. this.updateCacheCalled = false;
  87637. };
  87638. /**
  87639. * Updates the current device position and rotation in the babylon world
  87640. */
  87641. WebVRFreeCamera.prototype.update = function () {
  87642. // Get current device position in babylon world
  87643. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87644. // Get current device rotation in babylon world
  87645. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87646. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87647. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87648. _super.prototype.update.call(this);
  87649. };
  87650. /**
  87651. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87652. * @returns an identity matrix
  87653. */
  87654. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87655. return BABYLON.Matrix.Identity();
  87656. };
  87657. /**
  87658. * This function is called by the two RIG cameras.
  87659. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87660. */
  87661. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87662. var _this = this;
  87663. // Update the parent camera prior to using a child camera to avoid desynchronization
  87664. var parentCamera = this._cameraRigParams["parentCamera"];
  87665. parentCamera._updateCache();
  87666. //WebVR 1.1
  87667. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87668. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87669. if (!this.getScene().useRightHandedSystem) {
  87670. [2, 6, 8, 9, 14].forEach(function (num) {
  87671. _this._webvrViewMatrix.m[num] *= -1;
  87672. });
  87673. }
  87674. // update the camera rotation matrix
  87675. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87676. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87677. // Computing target and final matrix
  87678. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87679. // should the view matrix be updated with scale and position offset?
  87680. if (parentCamera.deviceScaleFactor !== 1) {
  87681. this._webvrViewMatrix.invert();
  87682. // scale the position, if set
  87683. if (parentCamera.deviceScaleFactor) {
  87684. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87685. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87686. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87687. }
  87688. this._webvrViewMatrix.invert();
  87689. }
  87690. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87691. // Compute global position
  87692. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87693. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87694. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87695. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87696. this._markSyncedWithParent();
  87697. return this._webvrViewMatrix;
  87698. };
  87699. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87700. var _this = this;
  87701. var parentCamera = this.parent;
  87702. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87703. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87704. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87705. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87706. //babylon compatible matrix
  87707. if (!this.getScene().useRightHandedSystem) {
  87708. [8, 9, 10, 11].forEach(function (num) {
  87709. _this._projectionMatrix.m[num] *= -1;
  87710. });
  87711. }
  87712. return this._projectionMatrix;
  87713. };
  87714. /**
  87715. * Initializes the controllers and their meshes
  87716. */
  87717. WebVRFreeCamera.prototype.initControllers = function () {
  87718. var _this = this;
  87719. this.controllers = [];
  87720. var manager = this.getScene().gamepadManager;
  87721. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87722. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87723. var webVrController = gamepad;
  87724. if (webVrController.defaultModel) {
  87725. webVrController.defaultModel.setEnabled(false);
  87726. }
  87727. if (webVrController.hand === "right") {
  87728. _this._rightController = null;
  87729. }
  87730. if (webVrController.hand === "left") {
  87731. _this._leftController = null;
  87732. }
  87733. var controllerIndex = _this.controllers.indexOf(webVrController);
  87734. if (controllerIndex !== -1) {
  87735. _this.controllers.splice(controllerIndex, 1);
  87736. }
  87737. }
  87738. });
  87739. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87740. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87741. var webVrController_1 = gamepad;
  87742. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87743. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87744. if (_this.webVROptions.controllerMeshes) {
  87745. if (webVrController_1.defaultModel) {
  87746. webVrController_1.defaultModel.setEnabled(true);
  87747. }
  87748. else {
  87749. // Load the meshes
  87750. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87751. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87752. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87753. if (_this.webVROptions.defaultLightingOnControllers) {
  87754. if (!_this._lightOnControllers) {
  87755. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87756. }
  87757. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87758. var children = mesh.getChildren();
  87759. if (children.length !== 0) {
  87760. children.forEach(function (mesh) {
  87761. light.includedOnlyMeshes.push(mesh);
  87762. activateLightOnSubMeshes_1(mesh, light);
  87763. });
  87764. }
  87765. };
  87766. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87767. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87768. }
  87769. });
  87770. }
  87771. }
  87772. webVrController_1.attachToPoseControlledCamera(_this);
  87773. // since this is async - sanity check. Is the controller already stored?
  87774. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87775. //add to the controllers array
  87776. _this.controllers.push(webVrController_1);
  87777. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87778. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87779. // So we're overriding setting left & right manually to be sure
  87780. var firstViveWandDetected = false;
  87781. for (var i = 0; i < _this.controllers.length; i++) {
  87782. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87783. if (!firstViveWandDetected) {
  87784. firstViveWandDetected = true;
  87785. _this.controllers[i].hand = "left";
  87786. }
  87787. else {
  87788. _this.controllers[i].hand = "right";
  87789. }
  87790. }
  87791. }
  87792. //did we find enough controllers? Great! let the developer know.
  87793. if (_this.controllers.length >= 2) {
  87794. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87795. }
  87796. }
  87797. }
  87798. });
  87799. };
  87800. return WebVRFreeCamera;
  87801. }(BABYLON.FreeCamera));
  87802. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87803. })(BABYLON || (BABYLON = {}));
  87804. //# sourceMappingURL=babylon.webVRCamera.js.map
  87805. var BABYLON;
  87806. (function (BABYLON) {
  87807. // We're mainly based on the logic defined into the FreeCamera code
  87808. /**
  87809. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87810. * being tilted forward or back and left or right.
  87811. */
  87812. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87813. __extends(DeviceOrientationCamera, _super);
  87814. /**
  87815. * Creates a new device orientation camera
  87816. * @param name The name of the camera
  87817. * @param position The start position camera
  87818. * @param scene The scene the camera belongs to
  87819. */
  87820. function DeviceOrientationCamera(name, position, scene) {
  87821. var _this = _super.call(this, name, position, scene) || this;
  87822. _this._quaternionCache = new BABYLON.Quaternion();
  87823. _this.inputs.addDeviceOrientation();
  87824. return _this;
  87825. }
  87826. /**
  87827. * Gets the current instance class name ("DeviceOrientationCamera").
  87828. * This helps avoiding instanceof at run time.
  87829. * @returns the class name
  87830. */
  87831. DeviceOrientationCamera.prototype.getClassName = function () {
  87832. return "DeviceOrientationCamera";
  87833. };
  87834. /**
  87835. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87836. */
  87837. DeviceOrientationCamera.prototype._checkInputs = function () {
  87838. _super.prototype._checkInputs.call(this);
  87839. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87840. if (this._initialQuaternion) {
  87841. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87842. }
  87843. };
  87844. /**
  87845. * Reset the camera to its default orientation on the specified axis only.
  87846. * @param axis The axis to reset
  87847. */
  87848. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87849. var _this = this;
  87850. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87851. //can only work if this camera has a rotation quaternion already.
  87852. if (!this.rotationQuaternion)
  87853. return;
  87854. if (!this._initialQuaternion) {
  87855. this._initialQuaternion = new BABYLON.Quaternion();
  87856. }
  87857. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87858. ['x', 'y', 'z'].forEach(function (axisName) {
  87859. if (!axis[axisName]) {
  87860. _this._initialQuaternion[axisName] = 0;
  87861. }
  87862. else {
  87863. _this._initialQuaternion[axisName] *= -1;
  87864. }
  87865. });
  87866. this._initialQuaternion.normalize();
  87867. //force rotation update
  87868. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87869. };
  87870. return DeviceOrientationCamera;
  87871. }(BABYLON.FreeCamera));
  87872. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87873. })(BABYLON || (BABYLON = {}));
  87874. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87875. var BABYLON;
  87876. (function (BABYLON) {
  87877. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87878. __extends(VRDeviceOrientationFreeCamera, _super);
  87879. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87880. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87881. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87882. var _this = _super.call(this, name, position, scene) || this;
  87883. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87884. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87885. return _this;
  87886. }
  87887. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87888. return "VRDeviceOrientationFreeCamera";
  87889. };
  87890. return VRDeviceOrientationFreeCamera;
  87891. }(BABYLON.DeviceOrientationCamera));
  87892. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87893. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87894. __extends(VRDeviceOrientationGamepadCamera, _super);
  87895. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87896. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87897. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87898. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87899. _this.inputs.addGamepad();
  87900. return _this;
  87901. }
  87902. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87903. return "VRDeviceOrientationGamepadCamera";
  87904. };
  87905. return VRDeviceOrientationGamepadCamera;
  87906. }(VRDeviceOrientationFreeCamera));
  87907. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87908. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87909. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87910. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87911. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87912. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87913. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87914. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87915. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87916. _this.inputs.addVRDeviceOrientation();
  87917. return _this;
  87918. }
  87919. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87920. return "VRDeviceOrientationArcRotateCamera";
  87921. };
  87922. return VRDeviceOrientationArcRotateCamera;
  87923. }(BABYLON.ArcRotateCamera));
  87924. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87925. })(BABYLON || (BABYLON = {}));
  87926. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87927. var BABYLON;
  87928. (function (BABYLON) {
  87929. /**
  87930. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87931. */
  87932. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87933. __extends(AnaglyphFreeCamera, _super);
  87934. /**
  87935. * Creates a new AnaglyphFreeCamera
  87936. * @param name defines camera name
  87937. * @param position defines initial position
  87938. * @param interaxialDistance defines distance between each color axis
  87939. * @param scene defines the hosting scene
  87940. */
  87941. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87942. var _this = _super.call(this, name, position, scene) || this;
  87943. _this.interaxialDistance = interaxialDistance;
  87944. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87945. return _this;
  87946. }
  87947. /**
  87948. * Gets camera class name
  87949. * @returns AnaglyphFreeCamera
  87950. */
  87951. AnaglyphFreeCamera.prototype.getClassName = function () {
  87952. return "AnaglyphFreeCamera";
  87953. };
  87954. return AnaglyphFreeCamera;
  87955. }(BABYLON.FreeCamera));
  87956. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87957. /**
  87958. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87959. */
  87960. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87961. __extends(AnaglyphArcRotateCamera, _super);
  87962. /**
  87963. * Creates a new AnaglyphArcRotateCamera
  87964. * @param name defines camera name
  87965. * @param alpha defines alpha angle (in radians)
  87966. * @param beta defines beta angle (in radians)
  87967. * @param radius defines radius
  87968. * @param target defines camera target
  87969. * @param interaxialDistance defines distance between each color axis
  87970. * @param scene defines the hosting scene
  87971. */
  87972. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87973. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87974. _this.interaxialDistance = interaxialDistance;
  87975. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87976. return _this;
  87977. }
  87978. /**
  87979. * Gets camera class name
  87980. * @returns AnaglyphArcRotateCamera
  87981. */
  87982. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87983. return "AnaglyphArcRotateCamera";
  87984. };
  87985. return AnaglyphArcRotateCamera;
  87986. }(BABYLON.ArcRotateCamera));
  87987. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87988. /**
  87989. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87990. */
  87991. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87992. __extends(AnaglyphGamepadCamera, _super);
  87993. /**
  87994. * Creates a new AnaglyphGamepadCamera
  87995. * @param name defines camera name
  87996. * @param position defines initial position
  87997. * @param interaxialDistance defines distance between each color axis
  87998. * @param scene defines the hosting scene
  87999. */
  88000. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  88001. var _this = _super.call(this, name, position, scene) || this;
  88002. _this.interaxialDistance = interaxialDistance;
  88003. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88004. return _this;
  88005. }
  88006. /**
  88007. * Gets camera class name
  88008. * @returns AnaglyphGamepadCamera
  88009. */
  88010. AnaglyphGamepadCamera.prototype.getClassName = function () {
  88011. return "AnaglyphGamepadCamera";
  88012. };
  88013. return AnaglyphGamepadCamera;
  88014. }(BABYLON.GamepadCamera));
  88015. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  88016. /**
  88017. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  88018. */
  88019. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  88020. __extends(AnaglyphUniversalCamera, _super);
  88021. /**
  88022. * Creates a new AnaglyphUniversalCamera
  88023. * @param name defines camera name
  88024. * @param position defines initial position
  88025. * @param interaxialDistance defines distance between each color axis
  88026. * @param scene defines the hosting scene
  88027. */
  88028. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  88029. var _this = _super.call(this, name, position, scene) || this;
  88030. _this.interaxialDistance = interaxialDistance;
  88031. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88032. return _this;
  88033. }
  88034. /**
  88035. * Gets camera class name
  88036. * @returns AnaglyphUniversalCamera
  88037. */
  88038. AnaglyphUniversalCamera.prototype.getClassName = function () {
  88039. return "AnaglyphUniversalCamera";
  88040. };
  88041. return AnaglyphUniversalCamera;
  88042. }(BABYLON.UniversalCamera));
  88043. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  88044. /**
  88045. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  88046. */
  88047. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  88048. __extends(StereoscopicFreeCamera, _super);
  88049. /**
  88050. * Creates a new StereoscopicFreeCamera
  88051. * @param name defines camera name
  88052. * @param position defines initial position
  88053. * @param interaxialDistance defines distance between each color axis
  88054. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88055. * @param scene defines the hosting scene
  88056. */
  88057. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88058. var _this = _super.call(this, name, position, scene) || this;
  88059. _this.interaxialDistance = interaxialDistance;
  88060. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88061. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88062. return _this;
  88063. }
  88064. /**
  88065. * Gets camera class name
  88066. * @returns StereoscopicFreeCamera
  88067. */
  88068. StereoscopicFreeCamera.prototype.getClassName = function () {
  88069. return "StereoscopicFreeCamera";
  88070. };
  88071. return StereoscopicFreeCamera;
  88072. }(BABYLON.FreeCamera));
  88073. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  88074. /**
  88075. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  88076. */
  88077. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  88078. __extends(StereoscopicArcRotateCamera, _super);
  88079. /**
  88080. * Creates a new StereoscopicArcRotateCamera
  88081. * @param name defines camera name
  88082. * @param alpha defines alpha angle (in radians)
  88083. * @param beta defines beta angle (in radians)
  88084. * @param radius defines radius
  88085. * @param target defines camera target
  88086. * @param interaxialDistance defines distance between each color axis
  88087. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88088. * @param scene defines the hosting scene
  88089. */
  88090. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  88091. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88092. _this.interaxialDistance = interaxialDistance;
  88093. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88094. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88095. return _this;
  88096. }
  88097. /**
  88098. * Gets camera class name
  88099. * @returns StereoscopicArcRotateCamera
  88100. */
  88101. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  88102. return "StereoscopicArcRotateCamera";
  88103. };
  88104. return StereoscopicArcRotateCamera;
  88105. }(BABYLON.ArcRotateCamera));
  88106. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  88107. /**
  88108. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  88109. */
  88110. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  88111. __extends(StereoscopicGamepadCamera, _super);
  88112. /**
  88113. * Creates a new StereoscopicGamepadCamera
  88114. * @param name defines camera name
  88115. * @param position defines initial position
  88116. * @param interaxialDistance defines distance between each color axis
  88117. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88118. * @param scene defines the hosting scene
  88119. */
  88120. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88121. var _this = _super.call(this, name, position, scene) || this;
  88122. _this.interaxialDistance = interaxialDistance;
  88123. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88124. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88125. return _this;
  88126. }
  88127. /**
  88128. * Gets camera class name
  88129. * @returns StereoscopicGamepadCamera
  88130. */
  88131. StereoscopicGamepadCamera.prototype.getClassName = function () {
  88132. return "StereoscopicGamepadCamera";
  88133. };
  88134. return StereoscopicGamepadCamera;
  88135. }(BABYLON.GamepadCamera));
  88136. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  88137. /**
  88138. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  88139. */
  88140. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  88141. __extends(StereoscopicUniversalCamera, _super);
  88142. /**
  88143. * Creates a new StereoscopicUniversalCamera
  88144. * @param name defines camera name
  88145. * @param position defines initial position
  88146. * @param interaxialDistance defines distance between each color axis
  88147. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88148. * @param scene defines the hosting scene
  88149. */
  88150. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88151. var _this = _super.call(this, name, position, scene) || this;
  88152. _this.interaxialDistance = interaxialDistance;
  88153. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88154. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88155. return _this;
  88156. }
  88157. /**
  88158. * Gets camera class name
  88159. * @returns StereoscopicUniversalCamera
  88160. */
  88161. StereoscopicUniversalCamera.prototype.getClassName = function () {
  88162. return "StereoscopicUniversalCamera";
  88163. };
  88164. return StereoscopicUniversalCamera;
  88165. }(BABYLON.UniversalCamera));
  88166. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  88167. })(BABYLON || (BABYLON = {}));
  88168. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  88169. var BABYLON;
  88170. (function (BABYLON) {
  88171. var VRExperienceHelperGazer = /** @class */ (function () {
  88172. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  88173. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  88174. this.scene = scene;
  88175. this._pointerDownOnMeshAsked = false;
  88176. this._isActionableMesh = false;
  88177. this._teleportationRequestInitiated = false;
  88178. this._teleportationBackRequestInitiated = false;
  88179. this._rotationRightAsked = false;
  88180. this._rotationLeftAsked = false;
  88181. this._dpadPressed = true;
  88182. this._activePointer = false;
  88183. this._id = VRExperienceHelperGazer._idCounter++;
  88184. // Gaze tracker
  88185. if (!gazeTrackerToClone) {
  88186. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  88187. this._gazeTracker.bakeCurrentTransformIntoVertices();
  88188. this._gazeTracker.isPickable = false;
  88189. this._gazeTracker.isVisible = false;
  88190. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  88191. targetMat.specularColor = BABYLON.Color3.Black();
  88192. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88193. targetMat.backFaceCulling = false;
  88194. this._gazeTracker.material = targetMat;
  88195. }
  88196. else {
  88197. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  88198. }
  88199. }
  88200. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  88201. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  88202. };
  88203. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  88204. this._pointerDownOnMeshAsked = true;
  88205. if (this._currentHit) {
  88206. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  88207. }
  88208. };
  88209. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  88210. if (this._currentHit) {
  88211. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  88212. }
  88213. this._pointerDownOnMeshAsked = false;
  88214. };
  88215. VRExperienceHelperGazer.prototype._activatePointer = function () {
  88216. this._activePointer = true;
  88217. };
  88218. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  88219. this._activePointer = false;
  88220. };
  88221. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  88222. if (distance === void 0) { distance = 100; }
  88223. };
  88224. VRExperienceHelperGazer.prototype.dispose = function () {
  88225. this._interactionsEnabled = false;
  88226. this._teleportationEnabled = false;
  88227. if (this._gazeTracker) {
  88228. this._gazeTracker.dispose();
  88229. }
  88230. };
  88231. VRExperienceHelperGazer._idCounter = 0;
  88232. return VRExperienceHelperGazer;
  88233. }());
  88234. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  88235. __extends(VRExperienceHelperControllerGazer, _super);
  88236. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  88237. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  88238. _this.webVRController = webVRController;
  88239. // Laser pointer
  88240. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  88241. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  88242. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88243. laserPointerMaterial.alpha = 0.6;
  88244. _this._laserPointer.material = laserPointerMaterial;
  88245. _this._laserPointer.rotation.x = Math.PI / 2;
  88246. _this._laserPointer.position.z = -0.5;
  88247. _this._laserPointer.isVisible = false;
  88248. if (!webVRController.mesh) {
  88249. // Create an empty mesh that is used prior to loading the high quality model
  88250. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  88251. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  88252. preloadPointerPose.rotation.x = -0.7;
  88253. preloadMesh.addChild(preloadPointerPose);
  88254. webVRController.attachToMesh(preloadMesh);
  88255. }
  88256. _this._setLaserPointerParent(webVRController.mesh);
  88257. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  88258. _this._setLaserPointerParent(mesh);
  88259. });
  88260. return _this;
  88261. }
  88262. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  88263. return this.webVRController.getForwardRay(length);
  88264. };
  88265. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  88266. _super.prototype._activatePointer.call(this);
  88267. this._laserPointer.isVisible = true;
  88268. };
  88269. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  88270. _super.prototype._deactivatePointer.call(this);
  88271. this._laserPointer.isVisible = false;
  88272. };
  88273. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  88274. this._laserPointer.material.emissiveColor = color;
  88275. };
  88276. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  88277. var makeNotPick = function (root) {
  88278. root.name += " laserPointer";
  88279. root.getChildMeshes().forEach(function (c) {
  88280. makeNotPick(c);
  88281. });
  88282. };
  88283. makeNotPick(mesh);
  88284. var childMeshes = mesh.getChildMeshes();
  88285. this.webVRController._pointingPoseNode = null;
  88286. for (var i = 0; i < childMeshes.length; i++) {
  88287. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  88288. mesh = childMeshes[i];
  88289. this.webVRController._pointingPoseNode = mesh;
  88290. break;
  88291. }
  88292. }
  88293. this._laserPointer.parent = mesh;
  88294. };
  88295. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  88296. if (distance === void 0) { distance = 100; }
  88297. this._laserPointer.scaling.y = distance;
  88298. this._laserPointer.position.z = -distance / 2;
  88299. };
  88300. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  88301. _super.prototype.dispose.call(this);
  88302. this._laserPointer.dispose();
  88303. if (this._meshAttachedObserver) {
  88304. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  88305. }
  88306. };
  88307. return VRExperienceHelperControllerGazer;
  88308. }(VRExperienceHelperGazer));
  88309. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  88310. __extends(VRExperienceHelperCameraGazer, _super);
  88311. function VRExperienceHelperCameraGazer(getCamera, scene) {
  88312. var _this = _super.call(this, scene) || this;
  88313. _this.getCamera = getCamera;
  88314. return _this;
  88315. }
  88316. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  88317. var camera = this.getCamera();
  88318. if (camera) {
  88319. return camera.getForwardRay(length);
  88320. }
  88321. else {
  88322. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  88323. }
  88324. };
  88325. return VRExperienceHelperCameraGazer;
  88326. }(VRExperienceHelperGazer));
  88327. /**
  88328. * Helps to quickly add VR support to an existing scene.
  88329. * See http://doc.babylonjs.com/how_to/webvr_helper
  88330. */
  88331. var VRExperienceHelper = /** @class */ (function () {
  88332. /**
  88333. * Instantiates a VRExperienceHelper.
  88334. * Helps to quickly add VR support to an existing scene.
  88335. * @param scene The scene the VRExperienceHelper belongs to.
  88336. * @param webVROptions Options to modify the vr experience helper's behavior.
  88337. */
  88338. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  88339. if (webVROptions === void 0) { webVROptions = {}; }
  88340. var _this = this;
  88341. this.webVROptions = webVROptions;
  88342. // Can the system support WebVR, even if a headset isn't plugged in?
  88343. this._webVRsupported = false;
  88344. // If WebVR is supported, is a headset plugged in and are we ready to present?
  88345. this._webVRready = false;
  88346. // Are we waiting for the requestPresent callback to complete?
  88347. this._webVRrequesting = false;
  88348. // Are we presenting to the headset right now?
  88349. this._webVRpresenting = false;
  88350. // Are we presenting in the fullscreen fallback?
  88351. this._fullscreenVRpresenting = false;
  88352. /**
  88353. * Observable raised when entering VR.
  88354. */
  88355. this.onEnteringVRObservable = new BABYLON.Observable();
  88356. /**
  88357. * Observable raised when exiting VR.
  88358. */
  88359. this.onExitingVRObservable = new BABYLON.Observable();
  88360. /**
  88361. * Observable raised when controller mesh is loaded.
  88362. */
  88363. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88364. this._useCustomVRButton = false;
  88365. this._teleportationRequested = false;
  88366. this._teleportActive = false;
  88367. this._floorMeshesCollection = [];
  88368. this._rotationAllowed = true;
  88369. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88370. this._isDefaultTeleportationTarget = true;
  88371. this._teleportationFillColor = "#444444";
  88372. this._teleportationBorderColor = "#FFFFFF";
  88373. this._rotationAngle = 0;
  88374. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88375. this._padSensibilityUp = 0.65;
  88376. this._padSensibilityDown = 0.35;
  88377. this.leftController = null;
  88378. this.rightController = null;
  88379. /**
  88380. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88381. */
  88382. this.onNewMeshSelected = new BABYLON.Observable();
  88383. /**
  88384. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88385. */
  88386. this.onNewMeshPicked = new BABYLON.Observable();
  88387. /**
  88388. * Observable raised before camera teleportation
  88389. */
  88390. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88391. /**
  88392. * Observable raised after camera teleportation
  88393. */
  88394. this.onAfterCameraTeleport = new BABYLON.Observable();
  88395. /**
  88396. * Observable raised when current selected mesh gets unselected
  88397. */
  88398. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88399. /**
  88400. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88401. */
  88402. this.teleportationEnabled = true;
  88403. this._teleportationInitialized = false;
  88404. this._interactionsEnabled = false;
  88405. this._interactionsRequested = false;
  88406. this._displayGaze = true;
  88407. this._displayLaserPointer = true;
  88408. this._onResize = function () {
  88409. _this.moveButtonToBottomRight();
  88410. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88411. _this.exitVR();
  88412. }
  88413. };
  88414. this._onFullscreenChange = function () {
  88415. if (document.fullscreen !== undefined) {
  88416. _this._fullscreenVRpresenting = document.fullscreen;
  88417. }
  88418. else if (document.mozFullScreen !== undefined) {
  88419. _this._fullscreenVRpresenting = document.mozFullScreen;
  88420. }
  88421. else if (document.webkitIsFullScreen !== undefined) {
  88422. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88423. }
  88424. else if (document.msIsFullScreen !== undefined) {
  88425. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88426. }
  88427. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88428. _this.exitVR();
  88429. if (!_this._useCustomVRButton) {
  88430. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88431. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88432. }
  88433. }
  88434. };
  88435. this.beforeRender = function () {
  88436. if (_this.leftController && _this.leftController._activePointer) {
  88437. _this._castRayAndSelectObject(_this.leftController);
  88438. }
  88439. if (_this.rightController && _this.rightController._activePointer) {
  88440. _this._castRayAndSelectObject(_this.rightController);
  88441. }
  88442. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88443. _this._castRayAndSelectObject(_this._cameraGazer);
  88444. }
  88445. else {
  88446. _this._cameraGazer._gazeTracker.isVisible = false;
  88447. }
  88448. };
  88449. this._onNewGamepadConnected = function (gamepad) {
  88450. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88451. if (gamepad.leftStick) {
  88452. gamepad.onleftstickchanged(function (stickValues) {
  88453. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88454. // Listening to classic/xbox gamepad only if no VR controller is active
  88455. if ((!_this.leftController && !_this.rightController) ||
  88456. ((_this.leftController && !_this.leftController._activePointer) &&
  88457. (_this.rightController && !_this.rightController._activePointer))) {
  88458. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88459. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88460. }
  88461. }
  88462. });
  88463. }
  88464. if (gamepad.rightStick) {
  88465. gamepad.onrightstickchanged(function (stickValues) {
  88466. if (_this._teleportationInitialized) {
  88467. _this._checkRotate(stickValues, _this._cameraGazer);
  88468. }
  88469. });
  88470. }
  88471. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88472. gamepad.onbuttondown(function (buttonPressed) {
  88473. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88474. _this._cameraGazer._selectionPointerDown();
  88475. }
  88476. });
  88477. gamepad.onbuttonup(function (buttonPressed) {
  88478. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88479. _this._cameraGazer._selectionPointerUp();
  88480. }
  88481. });
  88482. }
  88483. }
  88484. else {
  88485. var webVRController = gamepad;
  88486. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88487. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88488. _this.rightController = controller;
  88489. }
  88490. else {
  88491. _this.leftController = controller;
  88492. }
  88493. _this._tryEnableInteractionOnController(controller);
  88494. }
  88495. };
  88496. // 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
  88497. this._tryEnableInteractionOnController = function (controller) {
  88498. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88499. _this._enableInteractionOnController(controller);
  88500. }
  88501. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88502. _this._enableTeleportationOnController(controller);
  88503. }
  88504. };
  88505. this._onNewGamepadDisconnected = function (gamepad) {
  88506. if (gamepad instanceof BABYLON.WebVRController) {
  88507. if (gamepad.hand === "left" && _this.leftController != null) {
  88508. _this.leftController.dispose();
  88509. _this.leftController = null;
  88510. }
  88511. if (gamepad.hand === "right" && _this.rightController != null) {
  88512. _this.rightController.dispose();
  88513. _this.rightController = null;
  88514. }
  88515. }
  88516. };
  88517. this._workingVector = BABYLON.Vector3.Zero();
  88518. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88519. this._workingMatrix = BABYLON.Matrix.Identity();
  88520. this._scene = scene;
  88521. this._canvas = scene.getEngine().getRenderingCanvas();
  88522. // Parse options
  88523. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88524. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88525. }
  88526. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88527. webVROptions.createDeviceOrientationCamera = true;
  88528. }
  88529. if (webVROptions.laserToggle === undefined) {
  88530. webVROptions.laserToggle = true;
  88531. }
  88532. if (webVROptions.defaultHeight === undefined) {
  88533. webVROptions.defaultHeight = 1.7;
  88534. }
  88535. if (webVROptions.useCustomVRButton) {
  88536. this._useCustomVRButton = true;
  88537. if (webVROptions.customVRButton) {
  88538. this._btnVR = webVROptions.customVRButton;
  88539. }
  88540. }
  88541. if (webVROptions.rayLength) {
  88542. this._rayLength = webVROptions.rayLength;
  88543. }
  88544. this._defaultHeight = webVROptions.defaultHeight;
  88545. if (webVROptions.positionScale) {
  88546. this._rayLength *= webVROptions.positionScale;
  88547. this._defaultHeight *= webVROptions.positionScale;
  88548. }
  88549. // Set position
  88550. if (this._scene.activeCamera) {
  88551. this._position = this._scene.activeCamera.position.clone();
  88552. }
  88553. else {
  88554. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88555. }
  88556. // Set non-vr camera
  88557. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88558. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88559. // Copy data from existing camera
  88560. if (this._scene.activeCamera) {
  88561. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88562. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88563. // Set rotation from previous camera
  88564. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88565. var targetCamera = this._scene.activeCamera;
  88566. if (targetCamera.rotationQuaternion) {
  88567. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88568. }
  88569. else {
  88570. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88571. }
  88572. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88573. }
  88574. }
  88575. this._scene.activeCamera = this._deviceOrientationCamera;
  88576. if (this._canvas) {
  88577. this._scene.activeCamera.attachControl(this._canvas);
  88578. }
  88579. }
  88580. else {
  88581. this._existingCamera = this._scene.activeCamera;
  88582. }
  88583. // Create VR cameras
  88584. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88585. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88586. }
  88587. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88588. this._webVRCamera.useStandingMatrix();
  88589. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88590. // Create default button
  88591. if (!this._useCustomVRButton) {
  88592. this._btnVR = document.createElement("BUTTON");
  88593. this._btnVR.className = "babylonVRicon";
  88594. this._btnVR.id = "babylonVRiconbtn";
  88595. this._btnVR.title = "Click to switch to VR";
  88596. 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) }";
  88597. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88598. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88599. // css += ".babylonVRicon.vrdisplaysupported { }";
  88600. // css += ".babylonVRicon.vrdisplayready { }";
  88601. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88602. var style = document.createElement('style');
  88603. style.appendChild(document.createTextNode(css));
  88604. document.getElementsByTagName('head')[0].appendChild(style);
  88605. this.moveButtonToBottomRight();
  88606. }
  88607. // VR button click event
  88608. if (this._btnVR) {
  88609. this._btnVR.addEventListener("click", function () {
  88610. if (!_this.isInVRMode) {
  88611. _this.enterVR();
  88612. }
  88613. else {
  88614. _this.exitVR();
  88615. }
  88616. });
  88617. }
  88618. // Window events
  88619. window.addEventListener("resize", this._onResize);
  88620. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88621. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88622. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88623. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88624. // Display vr button when headset is connected
  88625. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88626. this.displayVRButton();
  88627. }
  88628. else {
  88629. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88630. if (e.vrDisplay) {
  88631. _this.displayVRButton();
  88632. }
  88633. });
  88634. }
  88635. // Exiting VR mode using 'ESC' key on desktop
  88636. this._onKeyDown = function (event) {
  88637. if (event.keyCode === 27 && _this.isInVRMode) {
  88638. _this.exitVR();
  88639. }
  88640. };
  88641. document.addEventListener("keydown", this._onKeyDown);
  88642. // Exiting VR mode double tapping the touch screen
  88643. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88644. if (_this.isInVRMode) {
  88645. _this.exitVR();
  88646. if (_this._fullscreenVRpresenting) {
  88647. _this._scene.getEngine().switchFullscreen(true);
  88648. }
  88649. }
  88650. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88651. // Listen for WebVR display changes
  88652. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88653. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88654. this._onVRRequestPresentStart = function () {
  88655. _this._webVRrequesting = true;
  88656. _this.updateButtonVisibility();
  88657. };
  88658. this._onVRRequestPresentComplete = function (success) {
  88659. _this._webVRrequesting = false;
  88660. _this.updateButtonVisibility();
  88661. };
  88662. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88663. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88664. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88665. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88666. scene.onDisposeObservable.add(function () {
  88667. _this.dispose();
  88668. });
  88669. // Gamepad connection events
  88670. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88671. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88672. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88673. this.updateButtonVisibility();
  88674. //create easing functions
  88675. this._circleEase = new BABYLON.CircleEase();
  88676. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88677. if (this.webVROptions.floorMeshes) {
  88678. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  88679. }
  88680. }
  88681. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88682. /** Return this.onEnteringVRObservable
  88683. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88684. */
  88685. get: function () {
  88686. return this.onEnteringVRObservable;
  88687. },
  88688. enumerable: true,
  88689. configurable: true
  88690. });
  88691. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88692. /** Return this.onExitingVRObservable
  88693. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88694. */
  88695. get: function () {
  88696. return this.onExitingVRObservable;
  88697. },
  88698. enumerable: true,
  88699. configurable: true
  88700. });
  88701. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88702. /** Return this.onControllerMeshLoadedObservable
  88703. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88704. */
  88705. get: function () {
  88706. return this.onControllerMeshLoadedObservable;
  88707. },
  88708. enumerable: true,
  88709. configurable: true
  88710. });
  88711. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88712. /**
  88713. * The mesh used to display where the user is going to teleport.
  88714. */
  88715. get: function () {
  88716. return this._teleportationTarget;
  88717. },
  88718. /**
  88719. * Sets the mesh to be used to display where the user is going to teleport.
  88720. */
  88721. set: function (value) {
  88722. if (value) {
  88723. value.name = "teleportationTarget";
  88724. this._isDefaultTeleportationTarget = false;
  88725. this._teleportationTarget = value;
  88726. }
  88727. },
  88728. enumerable: true,
  88729. configurable: true
  88730. });
  88731. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88732. /**
  88733. * The mesh used to display where the user is selecting,
  88734. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88735. * See http://doc.babylonjs.com/resources/baking_transformations
  88736. */
  88737. get: function () {
  88738. return this._cameraGazer._gazeTracker;
  88739. },
  88740. set: function (value) {
  88741. if (value) {
  88742. this._cameraGazer._gazeTracker = value;
  88743. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88744. this._cameraGazer._gazeTracker.isPickable = false;
  88745. this._cameraGazer._gazeTracker.isVisible = false;
  88746. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88747. if (this.leftController) {
  88748. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88749. }
  88750. if (this.rightController) {
  88751. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88752. }
  88753. }
  88754. },
  88755. enumerable: true,
  88756. configurable: true
  88757. });
  88758. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88759. /**
  88760. * If the ray of the gaze should be displayed.
  88761. */
  88762. get: function () {
  88763. return this._displayGaze;
  88764. },
  88765. /**
  88766. * Sets if the ray of the gaze should be displayed.
  88767. */
  88768. set: function (value) {
  88769. this._displayGaze = value;
  88770. if (!value) {
  88771. this._cameraGazer._gazeTracker.isVisible = false;
  88772. if (this.leftController) {
  88773. this.leftController._gazeTracker.isVisible = false;
  88774. }
  88775. if (this.rightController) {
  88776. this.rightController._gazeTracker.isVisible = false;
  88777. }
  88778. }
  88779. },
  88780. enumerable: true,
  88781. configurable: true
  88782. });
  88783. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88784. /**
  88785. * If the ray of the LaserPointer should be displayed.
  88786. */
  88787. get: function () {
  88788. return this._displayLaserPointer;
  88789. },
  88790. /**
  88791. * Sets if the ray of the LaserPointer should be displayed.
  88792. */
  88793. set: function (value) {
  88794. this._displayLaserPointer = value;
  88795. if (!value) {
  88796. if (this.rightController) {
  88797. this.rightController._deactivatePointer();
  88798. this.rightController._gazeTracker.isVisible = false;
  88799. }
  88800. if (this.leftController) {
  88801. this.leftController._deactivatePointer();
  88802. this.leftController._gazeTracker.isVisible = false;
  88803. }
  88804. }
  88805. else {
  88806. if (this.rightController) {
  88807. this.rightController._activatePointer();
  88808. }
  88809. if (this.leftController) {
  88810. this.leftController._activatePointer();
  88811. }
  88812. }
  88813. },
  88814. enumerable: true,
  88815. configurable: true
  88816. });
  88817. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88818. /**
  88819. * The deviceOrientationCamera used as the camera when not in VR.
  88820. */
  88821. get: function () {
  88822. return this._deviceOrientationCamera;
  88823. },
  88824. enumerable: true,
  88825. configurable: true
  88826. });
  88827. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88828. /**
  88829. * Based on the current WebVR support, returns the current VR camera used.
  88830. */
  88831. get: function () {
  88832. if (this._webVRready) {
  88833. return this._webVRCamera;
  88834. }
  88835. else {
  88836. return this._scene.activeCamera;
  88837. }
  88838. },
  88839. enumerable: true,
  88840. configurable: true
  88841. });
  88842. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88843. /**
  88844. * The webVRCamera which is used when in VR.
  88845. */
  88846. get: function () {
  88847. return this._webVRCamera;
  88848. },
  88849. enumerable: true,
  88850. configurable: true
  88851. });
  88852. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88853. /**
  88854. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88855. */
  88856. get: function () {
  88857. return this._vrDeviceOrientationCamera;
  88858. },
  88859. enumerable: true,
  88860. configurable: true
  88861. });
  88862. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88863. get: function () {
  88864. var result = this._cameraGazer._teleportationRequestInitiated
  88865. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88866. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88867. return result;
  88868. },
  88869. enumerable: true,
  88870. configurable: true
  88871. });
  88872. // Raised when one of the controller has loaded successfully its associated default mesh
  88873. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88874. if (this.leftController && this.leftController.webVRController == webVRController) {
  88875. if (webVRController.mesh) {
  88876. this.leftController._setLaserPointerParent(webVRController.mesh);
  88877. }
  88878. }
  88879. if (this.rightController && this.rightController.webVRController == webVRController) {
  88880. if (webVRController.mesh) {
  88881. this.rightController._setLaserPointerParent(webVRController.mesh);
  88882. }
  88883. }
  88884. try {
  88885. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88886. }
  88887. catch (err) {
  88888. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88889. }
  88890. };
  88891. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88892. /**
  88893. * Gets a value indicating if we are currently in VR mode.
  88894. */
  88895. get: function () {
  88896. return this._webVRpresenting || this._fullscreenVRpresenting;
  88897. },
  88898. enumerable: true,
  88899. configurable: true
  88900. });
  88901. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88902. var vrDisplay = this._scene.getEngine().getVRDevice();
  88903. if (vrDisplay) {
  88904. var wasPresenting = this._webVRpresenting;
  88905. // A VR display is connected
  88906. this._webVRpresenting = vrDisplay.isPresenting;
  88907. if (wasPresenting && !this._webVRpresenting)
  88908. this.exitVR();
  88909. }
  88910. else {
  88911. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88912. }
  88913. this.updateButtonVisibility();
  88914. };
  88915. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88916. this._webVRsupported = eventArgs.vrSupported;
  88917. this._webVRready = !!eventArgs.vrDisplay;
  88918. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88919. this.updateButtonVisibility();
  88920. };
  88921. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88922. if (this._canvas && !this._useCustomVRButton) {
  88923. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88924. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88925. }
  88926. };
  88927. VRExperienceHelper.prototype.displayVRButton = function () {
  88928. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88929. document.body.appendChild(this._btnVR);
  88930. this._btnVRDisplayed = true;
  88931. }
  88932. };
  88933. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88934. if (!this._btnVR || this._useCustomVRButton) {
  88935. return;
  88936. }
  88937. this._btnVR.className = "babylonVRicon";
  88938. if (this.isInVRMode) {
  88939. this._btnVR.className += " vrdisplaypresenting";
  88940. }
  88941. else {
  88942. if (this._webVRready)
  88943. this._btnVR.className += " vrdisplayready";
  88944. if (this._webVRsupported)
  88945. this._btnVR.className += " vrdisplaysupported";
  88946. if (this._webVRrequesting)
  88947. this._btnVR.className += " vrdisplayrequesting";
  88948. }
  88949. };
  88950. /**
  88951. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88952. * Otherwise, will use the fullscreen API.
  88953. */
  88954. VRExperienceHelper.prototype.enterVR = function () {
  88955. if (this.onEnteringVRObservable) {
  88956. try {
  88957. this.onEnteringVRObservable.notifyObservers(this);
  88958. }
  88959. catch (err) {
  88960. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88961. }
  88962. }
  88963. if (this._scene.activeCamera) {
  88964. this._position = this._scene.activeCamera.position.clone();
  88965. // make sure that we return to the last active camera
  88966. this._existingCamera = this._scene.activeCamera;
  88967. }
  88968. if (this._webVRrequesting)
  88969. return;
  88970. // If WebVR is supported and a headset is connected
  88971. if (this._webVRready) {
  88972. if (!this._webVRpresenting) {
  88973. this._webVRCamera.position = this._position;
  88974. this._scene.activeCamera = this._webVRCamera;
  88975. }
  88976. }
  88977. else if (this._vrDeviceOrientationCamera) {
  88978. this._vrDeviceOrientationCamera.position = this._position;
  88979. if (this._scene.activeCamera) {
  88980. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88981. }
  88982. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88983. this._scene.getEngine().switchFullscreen(true);
  88984. this.updateButtonVisibility();
  88985. }
  88986. if (this._scene.activeCamera && this._canvas) {
  88987. this._scene.activeCamera.attachControl(this._canvas);
  88988. }
  88989. if (this._interactionsEnabled) {
  88990. this._scene.registerBeforeRender(this.beforeRender);
  88991. }
  88992. };
  88993. /**
  88994. * Attempt to exit VR, or fullscreen.
  88995. */
  88996. VRExperienceHelper.prototype.exitVR = function () {
  88997. if (this.onExitingVRObservable) {
  88998. try {
  88999. this.onExitingVRObservable.notifyObservers(this);
  89000. }
  89001. catch (err) {
  89002. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  89003. }
  89004. }
  89005. if (this._webVRpresenting) {
  89006. this._scene.getEngine().disableVR();
  89007. }
  89008. if (this._scene.activeCamera) {
  89009. this._position = this._scene.activeCamera.position.clone();
  89010. }
  89011. if (this._deviceOrientationCamera) {
  89012. this._deviceOrientationCamera.position = this._position;
  89013. this._scene.activeCamera = this._deviceOrientationCamera;
  89014. if (this._canvas) {
  89015. this._scene.activeCamera.attachControl(this._canvas);
  89016. }
  89017. }
  89018. else if (this._existingCamera) {
  89019. this._existingCamera.position = this._position;
  89020. this._scene.activeCamera = this._existingCamera;
  89021. }
  89022. this.updateButtonVisibility();
  89023. if (this._interactionsEnabled) {
  89024. this._scene.unregisterBeforeRender(this.beforeRender);
  89025. }
  89026. // resize to update width and height when exiting vr exits fullscreen
  89027. this._scene.getEngine().resize();
  89028. };
  89029. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  89030. /**
  89031. * The position of the vr experience helper.
  89032. */
  89033. get: function () {
  89034. return this._position;
  89035. },
  89036. /**
  89037. * Sets the position of the vr experience helper.
  89038. */
  89039. set: function (value) {
  89040. this._position = value;
  89041. if (this._scene.activeCamera) {
  89042. this._scene.activeCamera.position = value;
  89043. }
  89044. },
  89045. enumerable: true,
  89046. configurable: true
  89047. });
  89048. /**
  89049. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  89050. */
  89051. VRExperienceHelper.prototype.enableInteractions = function () {
  89052. var _this = this;
  89053. if (!this._interactionsEnabled) {
  89054. this._interactionsRequested = true;
  89055. if (this.leftController) {
  89056. this._enableInteractionOnController(this.leftController);
  89057. }
  89058. if (this.rightController) {
  89059. this._enableInteractionOnController(this.rightController);
  89060. }
  89061. this.raySelectionPredicate = function (mesh) {
  89062. return mesh.isVisible;
  89063. };
  89064. this.meshSelectionPredicate = function (mesh) {
  89065. return true;
  89066. };
  89067. this._raySelectionPredicate = function (mesh) {
  89068. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  89069. && mesh.name.indexOf("teleportationTarget") === -1
  89070. && mesh.name.indexOf("torusTeleportation") === -1
  89071. && mesh.name.indexOf("laserPointer") === -1)) {
  89072. return _this.raySelectionPredicate(mesh);
  89073. }
  89074. return false;
  89075. };
  89076. this._interactionsEnabled = true;
  89077. }
  89078. };
  89079. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  89080. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  89081. if (this._floorMeshesCollection[i].id === mesh.id) {
  89082. return true;
  89083. }
  89084. }
  89085. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  89086. return true;
  89087. }
  89088. return false;
  89089. };
  89090. /**
  89091. * Adds a floor mesh to be used for teleportation.
  89092. * @param floorMesh the mesh to be used for teleportation.
  89093. */
  89094. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  89095. if (!this._floorMeshesCollection) {
  89096. return;
  89097. }
  89098. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  89099. return;
  89100. }
  89101. this._floorMeshesCollection.push(floorMesh);
  89102. };
  89103. /**
  89104. * Removes a floor mesh from being used for teleportation.
  89105. * @param floorMesh the mesh to be removed.
  89106. */
  89107. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  89108. if (!this._floorMeshesCollection) {
  89109. return;
  89110. }
  89111. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  89112. if (meshIndex !== -1) {
  89113. this._floorMeshesCollection.splice(meshIndex, 1);
  89114. }
  89115. };
  89116. /**
  89117. * Enables interactions and teleportation using the VR controllers and gaze.
  89118. * @param vrTeleportationOptions options to modify teleportation behavior.
  89119. */
  89120. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  89121. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  89122. if (!this._teleportationInitialized) {
  89123. this._teleportationRequested = true;
  89124. this.enableInteractions();
  89125. if (vrTeleportationOptions.floorMeshName) {
  89126. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  89127. }
  89128. if (vrTeleportationOptions.floorMeshes) {
  89129. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  89130. }
  89131. if (this.leftController != null) {
  89132. this._enableTeleportationOnController(this.leftController);
  89133. }
  89134. if (this.rightController != null) {
  89135. this._enableTeleportationOnController(this.rightController);
  89136. }
  89137. // Creates an image processing post process for the vignette not relying
  89138. // on the main scene configuration for image processing to reduce setup and spaces
  89139. // (gamma/linear) conflicts.
  89140. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  89141. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89142. imageProcessingConfiguration.vignetteEnabled = true;
  89143. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  89144. this._webVRCamera.detachPostProcess(this._postProcessMove);
  89145. this._teleportationInitialized = true;
  89146. if (this._isDefaultTeleportationTarget) {
  89147. this._createTeleportationCircles();
  89148. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  89149. }
  89150. }
  89151. };
  89152. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  89153. var _this = this;
  89154. var controllerMesh = controller.webVRController.mesh;
  89155. if (controllerMesh) {
  89156. controller._interactionsEnabled = true;
  89157. controller._activatePointer();
  89158. if (this.webVROptions.laserToggle) {
  89159. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  89160. // Enabling / disabling laserPointer
  89161. if (_this._displayLaserPointer && stateObject.value === 1) {
  89162. if (controller._activePointer) {
  89163. controller._deactivatePointer();
  89164. }
  89165. else {
  89166. controller._activatePointer();
  89167. }
  89168. if (_this.displayGaze) {
  89169. controller._gazeTracker.isVisible = controller._activePointer;
  89170. }
  89171. }
  89172. });
  89173. }
  89174. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  89175. if (!controller._pointerDownOnMeshAsked) {
  89176. if (stateObject.value > _this._padSensibilityUp) {
  89177. controller._selectionPointerDown();
  89178. }
  89179. }
  89180. else if (stateObject.value < _this._padSensibilityDown) {
  89181. controller._selectionPointerUp();
  89182. }
  89183. });
  89184. }
  89185. };
  89186. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  89187. // Dont teleport if another gaze already requested teleportation
  89188. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  89189. return;
  89190. }
  89191. if (!gazer._teleportationRequestInitiated) {
  89192. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  89193. gazer._activatePointer();
  89194. gazer._teleportationRequestInitiated = true;
  89195. }
  89196. }
  89197. else {
  89198. // Listening to the proper controller values changes to confirm teleportation
  89199. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  89200. if (this._teleportActive) {
  89201. this._teleportCamera(this._haloCenter);
  89202. }
  89203. gazer._teleportationRequestInitiated = false;
  89204. }
  89205. }
  89206. };
  89207. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  89208. // Only rotate when user is not currently selecting a teleportation location
  89209. if (gazer._teleportationRequestInitiated) {
  89210. return;
  89211. }
  89212. if (!gazer._rotationLeftAsked) {
  89213. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  89214. gazer._rotationLeftAsked = true;
  89215. if (this._rotationAllowed) {
  89216. this._rotateCamera(false);
  89217. }
  89218. }
  89219. }
  89220. else {
  89221. if (stateObject.x > -this._padSensibilityDown) {
  89222. gazer._rotationLeftAsked = false;
  89223. }
  89224. }
  89225. if (!gazer._rotationRightAsked) {
  89226. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  89227. gazer._rotationRightAsked = true;
  89228. if (this._rotationAllowed) {
  89229. this._rotateCamera(true);
  89230. }
  89231. }
  89232. }
  89233. else {
  89234. if (stateObject.x < this._padSensibilityDown) {
  89235. gazer._rotationRightAsked = false;
  89236. }
  89237. }
  89238. };
  89239. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  89240. // Only teleport backwards when user is not currently selecting a teleportation location
  89241. if (gazer._teleportationRequestInitiated) {
  89242. return;
  89243. }
  89244. // Teleport backwards
  89245. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  89246. if (!gazer._teleportationBackRequestInitiated) {
  89247. if (!this.currentVRCamera) {
  89248. return;
  89249. }
  89250. // Get rotation and position of the current camera
  89251. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  89252. var position = this.currentVRCamera.position;
  89253. // If the camera has device position, use that instead
  89254. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  89255. rotation = this.currentVRCamera.deviceRotationQuaternion;
  89256. position = this.currentVRCamera.devicePosition;
  89257. }
  89258. // Get matrix with only the y rotation of the device rotation
  89259. rotation.toEulerAnglesToRef(this._workingVector);
  89260. this._workingVector.z = 0;
  89261. this._workingVector.x = 0;
  89262. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  89263. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  89264. // Rotate backwards ray by device rotation to cast at the ground behind the user
  89265. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  89266. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  89267. var ray = new BABYLON.Ray(position, this._workingVector);
  89268. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89269. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  89270. this._teleportCamera(hit.pickedPoint);
  89271. }
  89272. gazer._teleportationBackRequestInitiated = true;
  89273. }
  89274. }
  89275. else {
  89276. gazer._teleportationBackRequestInitiated = false;
  89277. }
  89278. };
  89279. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  89280. var _this = this;
  89281. var controllerMesh = controller.webVRController.mesh;
  89282. if (controllerMesh) {
  89283. if (!controller._interactionsEnabled) {
  89284. this._enableInteractionOnController(controller);
  89285. }
  89286. controller._interactionsEnabled = true;
  89287. controller._teleportationEnabled = true;
  89288. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89289. controller._dpadPressed = false;
  89290. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  89291. controller._dpadPressed = stateObject.pressed;
  89292. if (!controller._dpadPressed) {
  89293. controller._rotationLeftAsked = false;
  89294. controller._rotationRightAsked = false;
  89295. controller._teleportationBackRequestInitiated = false;
  89296. }
  89297. });
  89298. }
  89299. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  89300. if (_this.teleportationEnabled) {
  89301. _this._checkTeleportBackwards(stateObject, controller);
  89302. _this._checkTeleportWithRay(stateObject, controller);
  89303. }
  89304. _this._checkRotate(stateObject, controller);
  89305. });
  89306. }
  89307. };
  89308. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  89309. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  89310. this._teleportationTarget.isPickable = false;
  89311. var length = 512;
  89312. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  89313. dynamicTexture.hasAlpha = true;
  89314. var context = dynamicTexture.getContext();
  89315. var centerX = length / 2;
  89316. var centerY = length / 2;
  89317. var radius = 200;
  89318. context.beginPath();
  89319. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  89320. context.fillStyle = this._teleportationFillColor;
  89321. context.fill();
  89322. context.lineWidth = 10;
  89323. context.strokeStyle = this._teleportationBorderColor;
  89324. context.stroke();
  89325. context.closePath();
  89326. dynamicTexture.update();
  89327. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  89328. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  89329. this._teleportationTarget.material = teleportationCircleMaterial;
  89330. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  89331. torus.isPickable = false;
  89332. torus.parent = this._teleportationTarget;
  89333. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89334. var keys = [];
  89335. keys.push({
  89336. frame: 0,
  89337. value: 0
  89338. });
  89339. keys.push({
  89340. frame: 30,
  89341. value: 0.4
  89342. });
  89343. keys.push({
  89344. frame: 60,
  89345. value: 0
  89346. });
  89347. animationInnerCircle.setKeys(keys);
  89348. var easingFunction = new BABYLON.SineEase();
  89349. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89350. animationInnerCircle.setEasingFunction(easingFunction);
  89351. torus.animations = [];
  89352. torus.animations.push(animationInnerCircle);
  89353. this._scene.beginAnimation(torus, 0, 60, true);
  89354. this._hideTeleportationTarget();
  89355. };
  89356. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  89357. this._teleportActive = true;
  89358. if (this._teleportationInitialized) {
  89359. this._teleportationTarget.isVisible = true;
  89360. if (this._isDefaultTeleportationTarget) {
  89361. this._teleportationTarget.getChildren()[0].isVisible = true;
  89362. }
  89363. }
  89364. };
  89365. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89366. this._teleportActive = false;
  89367. if (this._teleportationInitialized) {
  89368. this._teleportationTarget.isVisible = false;
  89369. if (this._isDefaultTeleportationTarget) {
  89370. this._teleportationTarget.getChildren()[0].isVisible = false;
  89371. }
  89372. }
  89373. };
  89374. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89375. var _this = this;
  89376. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89377. return;
  89378. }
  89379. if (right) {
  89380. this._rotationAngle++;
  89381. }
  89382. else {
  89383. this._rotationAngle--;
  89384. }
  89385. this.currentVRCamera.animations = [];
  89386. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89387. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89388. var animationRotationKeys = [];
  89389. animationRotationKeys.push({
  89390. frame: 0,
  89391. value: this.currentVRCamera.rotationQuaternion
  89392. });
  89393. animationRotationKeys.push({
  89394. frame: 6,
  89395. value: target
  89396. });
  89397. animationRotation.setKeys(animationRotationKeys);
  89398. animationRotation.setEasingFunction(this._circleEase);
  89399. this.currentVRCamera.animations.push(animationRotation);
  89400. this._postProcessMove.animations = [];
  89401. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89402. var vignetteWeightKeys = [];
  89403. vignetteWeightKeys.push({
  89404. frame: 0,
  89405. value: 0
  89406. });
  89407. vignetteWeightKeys.push({
  89408. frame: 3,
  89409. value: 4
  89410. });
  89411. vignetteWeightKeys.push({
  89412. frame: 6,
  89413. value: 0
  89414. });
  89415. animationPP.setKeys(vignetteWeightKeys);
  89416. animationPP.setEasingFunction(this._circleEase);
  89417. this._postProcessMove.animations.push(animationPP);
  89418. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89419. var vignetteStretchKeys = [];
  89420. vignetteStretchKeys.push({
  89421. frame: 0,
  89422. value: 0
  89423. });
  89424. vignetteStretchKeys.push({
  89425. frame: 3,
  89426. value: 10
  89427. });
  89428. vignetteStretchKeys.push({
  89429. frame: 6,
  89430. value: 0
  89431. });
  89432. animationPP2.setKeys(vignetteStretchKeys);
  89433. animationPP2.setEasingFunction(this._circleEase);
  89434. this._postProcessMove.animations.push(animationPP2);
  89435. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89436. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89437. this._postProcessMove.samples = 4;
  89438. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89439. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89440. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89441. });
  89442. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89443. };
  89444. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89445. if (hit.pickedPoint) {
  89446. if (gazer._teleportationRequestInitiated) {
  89447. this._displayTeleportationTarget();
  89448. this._haloCenter.copyFrom(hit.pickedPoint);
  89449. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89450. }
  89451. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89452. if (pickNormal) {
  89453. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89454. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89455. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89456. }
  89457. this._teleportationTarget.position.y += 0.1;
  89458. }
  89459. };
  89460. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89461. var _this = this;
  89462. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89463. return;
  89464. }
  89465. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89466. // offset of the headset from the anchor.
  89467. if (this.webVRCamera.leftCamera) {
  89468. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89469. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89470. location.subtractToRef(this._workingVector, this._workingVector);
  89471. }
  89472. else {
  89473. this._workingVector.copyFrom(location);
  89474. }
  89475. // Add height to account for user's height offset
  89476. if (this.isInVRMode) {
  89477. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89478. }
  89479. else {
  89480. this._workingVector.y += this._defaultHeight;
  89481. }
  89482. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89483. // Create animation from the camera's position to the new location
  89484. this.currentVRCamera.animations = [];
  89485. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89486. var animationCameraTeleportationKeys = [{
  89487. frame: 0,
  89488. value: this.currentVRCamera.position
  89489. },
  89490. {
  89491. frame: 11,
  89492. value: this._workingVector
  89493. }
  89494. ];
  89495. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89496. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89497. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89498. this._postProcessMove.animations = [];
  89499. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89500. var vignetteWeightKeys = [];
  89501. vignetteWeightKeys.push({
  89502. frame: 0,
  89503. value: 0
  89504. });
  89505. vignetteWeightKeys.push({
  89506. frame: 5,
  89507. value: 8
  89508. });
  89509. vignetteWeightKeys.push({
  89510. frame: 11,
  89511. value: 0
  89512. });
  89513. animationPP.setKeys(vignetteWeightKeys);
  89514. this._postProcessMove.animations.push(animationPP);
  89515. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89516. var vignetteStretchKeys = [];
  89517. vignetteStretchKeys.push({
  89518. frame: 0,
  89519. value: 0
  89520. });
  89521. vignetteStretchKeys.push({
  89522. frame: 5,
  89523. value: 10
  89524. });
  89525. vignetteStretchKeys.push({
  89526. frame: 11,
  89527. value: 0
  89528. });
  89529. animationPP2.setKeys(vignetteStretchKeys);
  89530. this._postProcessMove.animations.push(animationPP2);
  89531. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89532. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89533. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89534. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89535. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89536. });
  89537. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89538. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89539. });
  89540. this._hideTeleportationTarget();
  89541. };
  89542. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89543. if (normal) {
  89544. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89545. if (angle < Math.PI / 2) {
  89546. normal.scaleInPlace(-1);
  89547. }
  89548. }
  89549. return normal;
  89550. };
  89551. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89552. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89553. return;
  89554. }
  89555. var ray = gazer._getForwardRay(this._rayLength);
  89556. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89557. if (hit) {
  89558. // Populate the contrllers mesh that can be used for drag/drop
  89559. if (gazer._laserPointer) {
  89560. hit.originMesh = gazer._laserPointer.parent;
  89561. }
  89562. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  89563. }
  89564. gazer._currentHit = hit;
  89565. // Moving the gazeTracker on the mesh face targetted
  89566. if (hit && hit.pickedPoint) {
  89567. if (this._displayGaze) {
  89568. var multiplier = 1;
  89569. gazer._gazeTracker.isVisible = true;
  89570. if (gazer._isActionableMesh) {
  89571. multiplier = 3;
  89572. }
  89573. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89574. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89575. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89576. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89577. // To avoid z-fighting
  89578. var deltaFighting = 0.002;
  89579. if (pickNormal) {
  89580. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89581. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89582. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89583. }
  89584. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89585. if (gazer._gazeTracker.position.x < 0) {
  89586. gazer._gazeTracker.position.x += deltaFighting;
  89587. }
  89588. else {
  89589. gazer._gazeTracker.position.x -= deltaFighting;
  89590. }
  89591. if (gazer._gazeTracker.position.y < 0) {
  89592. gazer._gazeTracker.position.y += deltaFighting;
  89593. }
  89594. else {
  89595. gazer._gazeTracker.position.y -= deltaFighting;
  89596. }
  89597. if (gazer._gazeTracker.position.z < 0) {
  89598. gazer._gazeTracker.position.z += deltaFighting;
  89599. }
  89600. else {
  89601. gazer._gazeTracker.position.z -= deltaFighting;
  89602. }
  89603. }
  89604. // Changing the size of the laser pointer based on the distance from the targetted point
  89605. gazer._updatePointerDistance(hit.distance);
  89606. }
  89607. else {
  89608. gazer._updatePointerDistance();
  89609. gazer._gazeTracker.isVisible = false;
  89610. }
  89611. if (hit && hit.pickedMesh) {
  89612. // The object selected is the floor, we're in a teleportation scenario
  89613. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89614. // Moving the teleportation area to this targetted point
  89615. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89616. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89617. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89618. }
  89619. gazer._currentMeshSelected = null;
  89620. if (gazer._teleportationRequestInitiated) {
  89621. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89622. }
  89623. return;
  89624. }
  89625. // If not, we're in a selection scenario
  89626. //this._teleportationAllowed = false;
  89627. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89628. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89629. this.onNewMeshPicked.notifyObservers(hit);
  89630. gazer._currentMeshSelected = hit.pickedMesh;
  89631. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89632. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89633. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89634. gazer._isActionableMesh = true;
  89635. }
  89636. else {
  89637. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89638. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89639. gazer._isActionableMesh = false;
  89640. }
  89641. try {
  89642. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89643. }
  89644. catch (err) {
  89645. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89646. }
  89647. }
  89648. else {
  89649. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89650. gazer._currentMeshSelected = null;
  89651. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89652. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89653. }
  89654. }
  89655. }
  89656. else {
  89657. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89658. gazer._currentMeshSelected = null;
  89659. //this._teleportationAllowed = false;
  89660. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89661. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89662. }
  89663. };
  89664. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89665. if (mesh) {
  89666. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89667. }
  89668. };
  89669. /**
  89670. * Sets the color of the laser ray from the vr controllers.
  89671. * @param color new color for the ray.
  89672. */
  89673. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89674. if (this.leftController) {
  89675. this.leftController._setLaserPointerColor(color);
  89676. }
  89677. if (this.rightController) {
  89678. this.rightController._setLaserPointerColor(color);
  89679. }
  89680. };
  89681. /**
  89682. * Sets the color of the ray from the vr headsets gaze.
  89683. * @param color new color for the ray.
  89684. */
  89685. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89686. if (!this._cameraGazer._gazeTracker.material) {
  89687. return;
  89688. }
  89689. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89690. if (this.leftController) {
  89691. this.leftController._gazeTracker.material.emissiveColor = color;
  89692. }
  89693. if (this.rightController) {
  89694. this.rightController._gazeTracker.material.emissiveColor = color;
  89695. }
  89696. };
  89697. /**
  89698. * Exits VR and disposes of the vr experience helper
  89699. */
  89700. VRExperienceHelper.prototype.dispose = function () {
  89701. if (this.isInVRMode) {
  89702. this.exitVR();
  89703. }
  89704. if (this._postProcessMove) {
  89705. this._postProcessMove.dispose();
  89706. }
  89707. if (this._webVRCamera) {
  89708. this._webVRCamera.dispose();
  89709. }
  89710. if (this._vrDeviceOrientationCamera) {
  89711. this._vrDeviceOrientationCamera.dispose();
  89712. }
  89713. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89714. document.body.removeChild(this._btnVR);
  89715. }
  89716. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89717. this._deviceOrientationCamera.dispose();
  89718. }
  89719. if (this._cameraGazer) {
  89720. this._cameraGazer.dispose();
  89721. }
  89722. if (this.leftController) {
  89723. this.leftController.dispose();
  89724. }
  89725. if (this.rightController) {
  89726. this.rightController.dispose();
  89727. }
  89728. if (this._teleportationTarget) {
  89729. this._teleportationTarget.dispose();
  89730. }
  89731. this._floorMeshesCollection = [];
  89732. document.removeEventListener("keydown", this._onKeyDown);
  89733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89734. window.removeEventListener("resize", this._onResize);
  89735. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89736. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89737. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89738. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89739. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89740. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89741. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89742. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89743. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89744. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89745. this._scene.unregisterBeforeRender(this.beforeRender);
  89746. };
  89747. /**
  89748. * Gets the name of the VRExperienceHelper class
  89749. * @returns "VRExperienceHelper"
  89750. */
  89751. VRExperienceHelper.prototype.getClassName = function () {
  89752. return "VRExperienceHelper";
  89753. };
  89754. return VRExperienceHelper;
  89755. }());
  89756. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89757. })(BABYLON || (BABYLON = {}));
  89758. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89759. // Mainly based on these 2 articles :
  89760. // 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
  89761. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89762. var BABYLON;
  89763. (function (BABYLON) {
  89764. /**
  89765. * Defines the potential axis of a Joystick
  89766. */
  89767. var JoystickAxis;
  89768. (function (JoystickAxis) {
  89769. /** X axis */
  89770. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89771. /** Y axis */
  89772. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89773. /** Z axis */
  89774. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89775. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89776. /**
  89777. * Class used to define virtual joystick (used in touch mode)
  89778. */
  89779. var VirtualJoystick = /** @class */ (function () {
  89780. /**
  89781. * Creates a new virtual joystick
  89782. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89783. */
  89784. function VirtualJoystick(leftJoystick) {
  89785. var _this = this;
  89786. if (leftJoystick) {
  89787. this._leftJoystick = true;
  89788. }
  89789. else {
  89790. this._leftJoystick = false;
  89791. }
  89792. VirtualJoystick._globalJoystickIndex++;
  89793. // By default left & right arrow keys are moving the X
  89794. // and up & down keys are moving the Y
  89795. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89796. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89797. this.reverseLeftRight = false;
  89798. this.reverseUpDown = false;
  89799. // collections of pointers
  89800. this._touches = new BABYLON.StringDictionary();
  89801. this.deltaPosition = BABYLON.Vector3.Zero();
  89802. this._joystickSensibility = 25;
  89803. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89804. this._onResize = function (evt) {
  89805. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89806. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89807. if (VirtualJoystick.vjCanvas) {
  89808. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89809. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89810. }
  89811. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89812. };
  89813. // injecting a canvas element on top of the canvas 3D game
  89814. if (!VirtualJoystick.vjCanvas) {
  89815. window.addEventListener("resize", this._onResize, false);
  89816. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89817. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89818. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89819. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89820. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89821. VirtualJoystick.vjCanvas.style.width = "100%";
  89822. VirtualJoystick.vjCanvas.style.height = "100%";
  89823. VirtualJoystick.vjCanvas.style.position = "absolute";
  89824. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89825. VirtualJoystick.vjCanvas.style.top = "0px";
  89826. VirtualJoystick.vjCanvas.style.left = "0px";
  89827. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89828. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89829. // Support for jQuery PEP polyfill
  89830. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89831. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89832. if (!context) {
  89833. throw new Error("Unable to create canvas for virtual joystick");
  89834. }
  89835. VirtualJoystick.vjCanvasContext = context;
  89836. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89837. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89838. document.body.appendChild(VirtualJoystick.vjCanvas);
  89839. }
  89840. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89841. this.pressed = false;
  89842. // default joystick color
  89843. this._joystickColor = "cyan";
  89844. this._joystickPointerID = -1;
  89845. // current joystick position
  89846. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89847. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89848. // origin joystick position
  89849. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89850. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89851. this._onPointerDownHandlerRef = function (evt) {
  89852. _this._onPointerDown(evt);
  89853. };
  89854. this._onPointerMoveHandlerRef = function (evt) {
  89855. _this._onPointerMove(evt);
  89856. };
  89857. this._onPointerUpHandlerRef = function (evt) {
  89858. _this._onPointerUp(evt);
  89859. };
  89860. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89861. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89862. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89863. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89864. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89865. evt.preventDefault(); // Disables system menu
  89866. }, false);
  89867. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89868. }
  89869. /**
  89870. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89871. * @param newJoystickSensibility defines the new sensibility
  89872. */
  89873. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89874. this._joystickSensibility = newJoystickSensibility;
  89875. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89876. };
  89877. VirtualJoystick.prototype._onPointerDown = function (e) {
  89878. var positionOnScreenCondition;
  89879. e.preventDefault();
  89880. if (this._leftJoystick === true) {
  89881. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89882. }
  89883. else {
  89884. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89885. }
  89886. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89887. // First contact will be dedicated to the virtual joystick
  89888. this._joystickPointerID = e.pointerId;
  89889. this._joystickPointerStartPos.x = e.clientX;
  89890. this._joystickPointerStartPos.y = e.clientY;
  89891. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89892. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89893. this._deltaJoystickVector.x = 0;
  89894. this._deltaJoystickVector.y = 0;
  89895. this.pressed = true;
  89896. this._touches.add(e.pointerId.toString(), e);
  89897. }
  89898. else {
  89899. // You can only trigger the action buttons with a joystick declared
  89900. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89901. this._action();
  89902. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89903. }
  89904. }
  89905. };
  89906. VirtualJoystick.prototype._onPointerMove = function (e) {
  89907. // If the current pointer is the one associated to the joystick (first touch contact)
  89908. if (this._joystickPointerID == e.pointerId) {
  89909. this._joystickPointerPos.x = e.clientX;
  89910. this._joystickPointerPos.y = e.clientY;
  89911. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89912. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89913. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89914. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89915. switch (this._axisTargetedByLeftAndRight) {
  89916. case JoystickAxis.X:
  89917. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89918. break;
  89919. case JoystickAxis.Y:
  89920. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89921. break;
  89922. case JoystickAxis.Z:
  89923. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89924. break;
  89925. }
  89926. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89927. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89928. switch (this._axisTargetedByUpAndDown) {
  89929. case JoystickAxis.X:
  89930. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89931. break;
  89932. case JoystickAxis.Y:
  89933. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89934. break;
  89935. case JoystickAxis.Z:
  89936. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89937. break;
  89938. }
  89939. }
  89940. else {
  89941. var data = this._touches.get(e.pointerId.toString());
  89942. if (data) {
  89943. data.x = e.clientX;
  89944. data.y = e.clientY;
  89945. }
  89946. }
  89947. };
  89948. VirtualJoystick.prototype._onPointerUp = function (e) {
  89949. if (this._joystickPointerID == e.pointerId) {
  89950. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89951. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89952. this._joystickPointerID = -1;
  89953. this.pressed = false;
  89954. }
  89955. else {
  89956. var touch = this._touches.get(e.pointerId.toString());
  89957. if (touch) {
  89958. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89959. }
  89960. }
  89961. this._deltaJoystickVector.x = 0;
  89962. this._deltaJoystickVector.y = 0;
  89963. this._touches.remove(e.pointerId.toString());
  89964. };
  89965. /**
  89966. * Change the color of the virtual joystick
  89967. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89968. */
  89969. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89970. this._joystickColor = newColor;
  89971. };
  89972. /**
  89973. * Defines a callback to call when the joystick is touched
  89974. * @param action defines the callback
  89975. */
  89976. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89977. this._action = action;
  89978. };
  89979. /**
  89980. * Defines which axis you'd like to control for left & right
  89981. * @param axis defines the axis to use
  89982. */
  89983. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89984. switch (axis) {
  89985. case JoystickAxis.X:
  89986. case JoystickAxis.Y:
  89987. case JoystickAxis.Z:
  89988. this._axisTargetedByLeftAndRight = axis;
  89989. break;
  89990. default:
  89991. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89992. break;
  89993. }
  89994. };
  89995. /**
  89996. * Defines which axis you'd like to control for up & down
  89997. * @param axis defines the axis to use
  89998. */
  89999. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  90000. switch (axis) {
  90001. case JoystickAxis.X:
  90002. case JoystickAxis.Y:
  90003. case JoystickAxis.Z:
  90004. this._axisTargetedByUpAndDown = axis;
  90005. break;
  90006. default:
  90007. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  90008. break;
  90009. }
  90010. };
  90011. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  90012. var _this = this;
  90013. if (this.pressed) {
  90014. this._touches.forEach(function (key, touch) {
  90015. if (touch.pointerId === _this._joystickPointerID) {
  90016. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  90017. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  90018. VirtualJoystick.vjCanvasContext.beginPath();
  90019. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90020. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90021. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  90022. VirtualJoystick.vjCanvasContext.stroke();
  90023. VirtualJoystick.vjCanvasContext.closePath();
  90024. VirtualJoystick.vjCanvasContext.beginPath();
  90025. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90026. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90027. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  90028. VirtualJoystick.vjCanvasContext.stroke();
  90029. VirtualJoystick.vjCanvasContext.closePath();
  90030. VirtualJoystick.vjCanvasContext.beginPath();
  90031. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90032. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  90033. VirtualJoystick.vjCanvasContext.stroke();
  90034. VirtualJoystick.vjCanvasContext.closePath();
  90035. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  90036. }
  90037. else {
  90038. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90039. VirtualJoystick.vjCanvasContext.beginPath();
  90040. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  90041. VirtualJoystick.vjCanvasContext.beginPath();
  90042. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  90043. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90044. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  90045. VirtualJoystick.vjCanvasContext.stroke();
  90046. VirtualJoystick.vjCanvasContext.closePath();
  90047. touch.prevX = touch.x;
  90048. touch.prevY = touch.y;
  90049. }
  90050. ;
  90051. });
  90052. }
  90053. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90054. };
  90055. /**
  90056. * Release internal HTML canvas
  90057. */
  90058. VirtualJoystick.prototype.releaseCanvas = function () {
  90059. if (VirtualJoystick.vjCanvas) {
  90060. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  90061. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  90062. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  90063. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  90064. window.removeEventListener("resize", this._onResize);
  90065. document.body.removeChild(VirtualJoystick.vjCanvas);
  90066. VirtualJoystick.vjCanvas = null;
  90067. }
  90068. };
  90069. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  90070. VirtualJoystick._globalJoystickIndex = 0;
  90071. return VirtualJoystick;
  90072. }());
  90073. BABYLON.VirtualJoystick = VirtualJoystick;
  90074. })(BABYLON || (BABYLON = {}));
  90075. //# sourceMappingURL=babylon.virtualJoystick.js.map
  90076. var BABYLON;
  90077. (function (BABYLON) {
  90078. // We're mainly based on the logic defined into the FreeCamera code
  90079. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  90080. __extends(VirtualJoysticksCamera, _super);
  90081. function VirtualJoysticksCamera(name, position, scene) {
  90082. var _this = _super.call(this, name, position, scene) || this;
  90083. _this.inputs.addVirtualJoystick();
  90084. return _this;
  90085. }
  90086. VirtualJoysticksCamera.prototype.getClassName = function () {
  90087. return "VirtualJoysticksCamera";
  90088. };
  90089. return VirtualJoysticksCamera;
  90090. }(BABYLON.FreeCamera));
  90091. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  90092. })(BABYLON || (BABYLON = {}));
  90093. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  90094. var BABYLON;
  90095. (function (BABYLON) {
  90096. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  90097. function FreeCameraVirtualJoystickInput() {
  90098. }
  90099. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  90100. return this._leftjoystick;
  90101. };
  90102. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  90103. return this._rightjoystick;
  90104. };
  90105. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  90106. if (this._leftjoystick) {
  90107. var camera = this.camera;
  90108. var speed = camera._computeLocalCameraSpeed() * 50;
  90109. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  90110. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  90111. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  90112. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  90113. if (!this._leftjoystick.pressed) {
  90114. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  90115. }
  90116. if (!this._rightjoystick.pressed) {
  90117. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  90118. }
  90119. }
  90120. };
  90121. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  90122. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  90123. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  90124. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  90125. this._leftjoystick.setJoystickSensibility(0.15);
  90126. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  90127. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  90128. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  90129. this._rightjoystick.reverseUpDown = true;
  90130. this._rightjoystick.setJoystickSensibility(0.05);
  90131. this._rightjoystick.setJoystickColor("yellow");
  90132. };
  90133. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  90134. this._leftjoystick.releaseCanvas();
  90135. this._rightjoystick.releaseCanvas();
  90136. };
  90137. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  90138. return "FreeCameraVirtualJoystickInput";
  90139. };
  90140. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  90141. return "virtualJoystick";
  90142. };
  90143. return FreeCameraVirtualJoystickInput;
  90144. }());
  90145. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  90146. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  90147. })(BABYLON || (BABYLON = {}));
  90148. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  90149. var BABYLON;
  90150. (function (BABYLON) {
  90151. var SimplificationSettings = /** @class */ (function () {
  90152. function SimplificationSettings(quality, distance, optimizeMesh) {
  90153. this.quality = quality;
  90154. this.distance = distance;
  90155. this.optimizeMesh = optimizeMesh;
  90156. }
  90157. return SimplificationSettings;
  90158. }());
  90159. BABYLON.SimplificationSettings = SimplificationSettings;
  90160. var SimplificationQueue = /** @class */ (function () {
  90161. function SimplificationQueue() {
  90162. this.running = false;
  90163. this._simplificationArray = [];
  90164. }
  90165. SimplificationQueue.prototype.addTask = function (task) {
  90166. this._simplificationArray.push(task);
  90167. };
  90168. SimplificationQueue.prototype.executeNext = function () {
  90169. var task = this._simplificationArray.pop();
  90170. if (task) {
  90171. this.running = true;
  90172. this.runSimplification(task);
  90173. }
  90174. else {
  90175. this.running = false;
  90176. }
  90177. };
  90178. SimplificationQueue.prototype.runSimplification = function (task) {
  90179. var _this = this;
  90180. if (task.parallelProcessing) {
  90181. //parallel simplifier
  90182. task.settings.forEach(function (setting) {
  90183. var simplifier = _this.getSimplifier(task);
  90184. simplifier.simplify(setting, function (newMesh) {
  90185. task.mesh.addLODLevel(setting.distance, newMesh);
  90186. newMesh.isVisible = true;
  90187. //check if it is the last
  90188. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  90189. //all done, run the success callback.
  90190. task.successCallback();
  90191. }
  90192. _this.executeNext();
  90193. });
  90194. });
  90195. }
  90196. else {
  90197. //single simplifier.
  90198. var simplifier = this.getSimplifier(task);
  90199. var runDecimation = function (setting, callback) {
  90200. simplifier.simplify(setting, function (newMesh) {
  90201. task.mesh.addLODLevel(setting.distance, newMesh);
  90202. newMesh.isVisible = true;
  90203. //run the next quality level
  90204. callback();
  90205. });
  90206. };
  90207. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  90208. runDecimation(task.settings[loop.index], function () {
  90209. loop.executeNext();
  90210. });
  90211. }, function () {
  90212. //execution ended, run the success callback.
  90213. if (task.successCallback) {
  90214. task.successCallback();
  90215. }
  90216. _this.executeNext();
  90217. });
  90218. }
  90219. };
  90220. SimplificationQueue.prototype.getSimplifier = function (task) {
  90221. switch (task.simplificationType) {
  90222. case SimplificationType.QUADRATIC:
  90223. default:
  90224. return new QuadraticErrorSimplification(task.mesh);
  90225. }
  90226. };
  90227. return SimplificationQueue;
  90228. }());
  90229. BABYLON.SimplificationQueue = SimplificationQueue;
  90230. /**
  90231. * The implemented types of simplification
  90232. * At the moment only Quadratic Error Decimation is implemented
  90233. */
  90234. var SimplificationType;
  90235. (function (SimplificationType) {
  90236. /** Quadratic error decimation */
  90237. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  90238. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  90239. var DecimationTriangle = /** @class */ (function () {
  90240. function DecimationTriangle(vertices) {
  90241. this.vertices = vertices;
  90242. this.error = new Array(4);
  90243. this.deleted = false;
  90244. this.isDirty = false;
  90245. this.deletePending = false;
  90246. this.borderFactor = 0;
  90247. }
  90248. return DecimationTriangle;
  90249. }());
  90250. BABYLON.DecimationTriangle = DecimationTriangle;
  90251. var DecimationVertex = /** @class */ (function () {
  90252. function DecimationVertex(position, id) {
  90253. this.position = position;
  90254. this.id = id;
  90255. this.isBorder = true;
  90256. this.q = new QuadraticMatrix();
  90257. this.triangleCount = 0;
  90258. this.triangleStart = 0;
  90259. this.originalOffsets = [];
  90260. }
  90261. DecimationVertex.prototype.updatePosition = function (newPosition) {
  90262. this.position.copyFrom(newPosition);
  90263. };
  90264. return DecimationVertex;
  90265. }());
  90266. BABYLON.DecimationVertex = DecimationVertex;
  90267. var QuadraticMatrix = /** @class */ (function () {
  90268. function QuadraticMatrix(data) {
  90269. this.data = new Array(10);
  90270. for (var i = 0; i < 10; ++i) {
  90271. if (data && data[i]) {
  90272. this.data[i] = data[i];
  90273. }
  90274. else {
  90275. this.data[i] = 0;
  90276. }
  90277. }
  90278. }
  90279. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  90280. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  90281. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  90282. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  90283. return det;
  90284. };
  90285. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  90286. for (var i = 0; i < 10; ++i) {
  90287. this.data[i] += matrix.data[i];
  90288. }
  90289. };
  90290. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  90291. for (var i = 0; i < 10; ++i) {
  90292. this.data[i] += data[i];
  90293. }
  90294. };
  90295. QuadraticMatrix.prototype.add = function (matrix) {
  90296. var m = new QuadraticMatrix();
  90297. for (var i = 0; i < 10; ++i) {
  90298. m.data[i] = this.data[i] + matrix.data[i];
  90299. }
  90300. return m;
  90301. };
  90302. QuadraticMatrix.FromData = function (a, b, c, d) {
  90303. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  90304. };
  90305. //returning an array to avoid garbage collection
  90306. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  90307. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  90308. };
  90309. return QuadraticMatrix;
  90310. }());
  90311. BABYLON.QuadraticMatrix = QuadraticMatrix;
  90312. var Reference = /** @class */ (function () {
  90313. function Reference(vertexId, triangleId) {
  90314. this.vertexId = vertexId;
  90315. this.triangleId = triangleId;
  90316. }
  90317. return Reference;
  90318. }());
  90319. BABYLON.Reference = Reference;
  90320. /**
  90321. * An implementation of the Quadratic Error simplification algorithm.
  90322. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  90323. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  90324. * @author RaananW
  90325. */
  90326. var QuadraticErrorSimplification = /** @class */ (function () {
  90327. function QuadraticErrorSimplification(_mesh) {
  90328. this._mesh = _mesh;
  90329. this.syncIterations = 5000;
  90330. this.aggressiveness = 7;
  90331. this.decimationIterations = 100;
  90332. this.boundingBoxEpsilon = BABYLON.Epsilon;
  90333. }
  90334. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  90335. var _this = this;
  90336. this.initDecimatedMesh();
  90337. //iterating through the submeshes array, one after the other.
  90338. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  90339. _this.initWithMesh(loop.index, function () {
  90340. _this.runDecimation(settings, loop.index, function () {
  90341. loop.executeNext();
  90342. });
  90343. }, settings.optimizeMesh);
  90344. }, function () {
  90345. setTimeout(function () {
  90346. successCallback(_this._reconstructedMesh);
  90347. }, 0);
  90348. });
  90349. };
  90350. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  90351. var _this = this;
  90352. var targetCount = ~~(this.triangles.length * settings.quality);
  90353. var deletedTriangles = 0;
  90354. var triangleCount = this.triangles.length;
  90355. var iterationFunction = function (iteration, callback) {
  90356. setTimeout(function () {
  90357. if (iteration % 5 === 0) {
  90358. _this.updateMesh(iteration === 0);
  90359. }
  90360. for (var i = 0; i < _this.triangles.length; ++i) {
  90361. _this.triangles[i].isDirty = false;
  90362. }
  90363. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90364. var trianglesIterator = function (i) {
  90365. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90366. var t = _this.triangles[tIdx];
  90367. if (!t)
  90368. return;
  90369. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90370. return;
  90371. }
  90372. for (var j = 0; j < 3; ++j) {
  90373. if (t.error[j] < threshold) {
  90374. var deleted0 = [];
  90375. var deleted1 = [];
  90376. var v0 = t.vertices[j];
  90377. var v1 = t.vertices[(j + 1) % 3];
  90378. if (v0.isBorder || v1.isBorder)
  90379. continue;
  90380. var p = BABYLON.Vector3.Zero();
  90381. var n = BABYLON.Vector3.Zero();
  90382. var uv = BABYLON.Vector2.Zero();
  90383. var color = new BABYLON.Color4(0, 0, 0, 1);
  90384. _this.calculateError(v0, v1, p, n, uv, color);
  90385. var delTr = new Array();
  90386. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90387. continue;
  90388. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90389. continue;
  90390. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90391. continue;
  90392. var uniqueArray = new Array();
  90393. delTr.forEach(function (deletedT) {
  90394. if (uniqueArray.indexOf(deletedT) === -1) {
  90395. deletedT.deletePending = true;
  90396. uniqueArray.push(deletedT);
  90397. }
  90398. });
  90399. if (uniqueArray.length % 2 !== 0) {
  90400. continue;
  90401. }
  90402. v0.q = v1.q.add(v0.q);
  90403. v0.updatePosition(p);
  90404. var tStart = _this.references.length;
  90405. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90406. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90407. var tCount = _this.references.length - tStart;
  90408. if (tCount <= v0.triangleCount) {
  90409. if (tCount) {
  90410. for (var c = 0; c < tCount; c++) {
  90411. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90412. }
  90413. }
  90414. }
  90415. else {
  90416. v0.triangleStart = tStart;
  90417. }
  90418. v0.triangleCount = tCount;
  90419. break;
  90420. }
  90421. }
  90422. };
  90423. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90424. }, 0);
  90425. };
  90426. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90427. if (triangleCount - deletedTriangles <= targetCount)
  90428. loop.breakLoop();
  90429. else {
  90430. iterationFunction(loop.index, function () {
  90431. loop.executeNext();
  90432. });
  90433. }
  90434. }, function () {
  90435. setTimeout(function () {
  90436. //reconstruct this part of the mesh
  90437. _this.reconstructMesh(submeshIndex);
  90438. successCallback();
  90439. }, 0);
  90440. });
  90441. };
  90442. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90443. var _this = this;
  90444. this.vertices = [];
  90445. this.triangles = [];
  90446. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90447. var indices = this._mesh.getIndices();
  90448. var submesh = this._mesh.subMeshes[submeshIndex];
  90449. var findInVertices = function (positionToSearch) {
  90450. if (optimizeMesh) {
  90451. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90452. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90453. return _this.vertices[ii];
  90454. }
  90455. }
  90456. }
  90457. return null;
  90458. };
  90459. var vertexReferences = [];
  90460. var vertexInit = function (i) {
  90461. if (!positionData) {
  90462. return;
  90463. }
  90464. var offset = i + submesh.verticesStart;
  90465. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90466. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90467. vertex.originalOffsets.push(offset);
  90468. if (vertex.id === _this.vertices.length) {
  90469. _this.vertices.push(vertex);
  90470. }
  90471. vertexReferences.push(vertex.id);
  90472. };
  90473. //var totalVertices = mesh.getTotalVertices();
  90474. var totalVertices = submesh.verticesCount;
  90475. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90476. var indicesInit = function (i) {
  90477. if (!indices) {
  90478. return;
  90479. }
  90480. var offset = (submesh.indexStart / 3) + i;
  90481. var pos = (offset * 3);
  90482. var i0 = indices[pos + 0];
  90483. var i1 = indices[pos + 1];
  90484. var i2 = indices[pos + 2];
  90485. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90486. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90487. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90488. var triangle = new DecimationTriangle([v0, v1, v2]);
  90489. triangle.originalOffset = pos;
  90490. _this.triangles.push(triangle);
  90491. };
  90492. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90493. _this.init(callback);
  90494. });
  90495. });
  90496. };
  90497. QuadraticErrorSimplification.prototype.init = function (callback) {
  90498. var _this = this;
  90499. var triangleInit1 = function (i) {
  90500. var t = _this.triangles[i];
  90501. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90502. for (var j = 0; j < 3; j++) {
  90503. 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))));
  90504. }
  90505. };
  90506. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90507. var triangleInit2 = function (i) {
  90508. var t = _this.triangles[i];
  90509. for (var j = 0; j < 3; ++j) {
  90510. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90511. }
  90512. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90513. };
  90514. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90515. callback();
  90516. });
  90517. });
  90518. };
  90519. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90520. var newTriangles = [];
  90521. var i;
  90522. for (i = 0; i < this.vertices.length; ++i) {
  90523. this.vertices[i].triangleCount = 0;
  90524. }
  90525. var t;
  90526. var j;
  90527. for (i = 0; i < this.triangles.length; ++i) {
  90528. if (!this.triangles[i].deleted) {
  90529. t = this.triangles[i];
  90530. for (j = 0; j < 3; ++j) {
  90531. t.vertices[j].triangleCount = 1;
  90532. }
  90533. newTriangles.push(t);
  90534. }
  90535. }
  90536. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90537. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90538. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90539. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90540. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90541. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90542. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90543. var vertexCount = 0;
  90544. for (i = 0; i < this.vertices.length; ++i) {
  90545. var vertex = this.vertices[i];
  90546. vertex.id = vertexCount;
  90547. if (vertex.triangleCount) {
  90548. vertex.originalOffsets.forEach(function (originalOffset) {
  90549. if (!normalData) {
  90550. return;
  90551. }
  90552. newPositionData.push(vertex.position.x);
  90553. newPositionData.push(vertex.position.y);
  90554. newPositionData.push(vertex.position.z);
  90555. newNormalData.push(normalData[originalOffset * 3]);
  90556. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90557. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90558. if (uvs && uvs.length) {
  90559. newUVsData.push(uvs[(originalOffset * 2)]);
  90560. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90561. }
  90562. else if (colorsData && colorsData.length) {
  90563. newColorsData.push(colorsData[(originalOffset * 4)]);
  90564. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90565. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90566. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90567. }
  90568. ++vertexCount;
  90569. });
  90570. }
  90571. }
  90572. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90573. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90574. var submeshesArray = this._reconstructedMesh.subMeshes;
  90575. this._reconstructedMesh.subMeshes = [];
  90576. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90577. var originalIndices = this._mesh.getIndices();
  90578. for (i = 0; i < newTriangles.length; ++i) {
  90579. t = newTriangles[i]; //now get the new referencing point for each vertex
  90580. [0, 1, 2].forEach(function (idx) {
  90581. var id = originalIndices[t.originalOffset + idx];
  90582. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90583. if (offset < 0)
  90584. offset = 0;
  90585. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90586. });
  90587. }
  90588. //overwriting the old vertex buffers and indices.
  90589. this._reconstructedMesh.setIndices(newIndicesArray);
  90590. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90591. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90592. if (newUVsData.length > 0)
  90593. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90594. if (newColorsData.length > 0)
  90595. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90596. //create submesh
  90597. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90598. if (submeshIndex > 0) {
  90599. this._reconstructedMesh.subMeshes = [];
  90600. submeshesArray.forEach(function (submesh) {
  90601. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90602. });
  90603. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90604. }
  90605. };
  90606. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90607. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90608. this._reconstructedMesh.material = this._mesh.material;
  90609. this._reconstructedMesh.parent = this._mesh.parent;
  90610. this._reconstructedMesh.isVisible = false;
  90611. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90612. };
  90613. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90614. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90615. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90616. if (t.deleted)
  90617. continue;
  90618. var s = this.references[vertex1.triangleStart + i].vertexId;
  90619. var v1 = t.vertices[(s + 1) % 3];
  90620. var v2 = t.vertices[(s + 2) % 3];
  90621. if ((v1 === vertex2 || v2 === vertex2)) {
  90622. deletedArray[i] = true;
  90623. delTr.push(t);
  90624. continue;
  90625. }
  90626. var d1 = v1.position.subtract(point);
  90627. d1 = d1.normalize();
  90628. var d2 = v2.position.subtract(point);
  90629. d2 = d2.normalize();
  90630. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90631. return true;
  90632. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90633. deletedArray[i] = false;
  90634. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90635. return true;
  90636. }
  90637. return false;
  90638. };
  90639. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90640. var newDeleted = deletedTriangles;
  90641. for (var i = 0; i < vertex.triangleCount; ++i) {
  90642. var ref = this.references[vertex.triangleStart + i];
  90643. var t = this.triangles[ref.triangleId];
  90644. if (t.deleted)
  90645. continue;
  90646. if (deletedArray[i] && t.deletePending) {
  90647. t.deleted = true;
  90648. newDeleted++;
  90649. continue;
  90650. }
  90651. t.vertices[ref.vertexId] = origVertex;
  90652. t.isDirty = true;
  90653. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90654. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90655. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90656. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90657. this.references.push(ref);
  90658. }
  90659. return newDeleted;
  90660. };
  90661. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90662. for (var i = 0; i < this.vertices.length; ++i) {
  90663. var vCount = [];
  90664. var vId = [];
  90665. var v = this.vertices[i];
  90666. var j;
  90667. for (j = 0; j < v.triangleCount; ++j) {
  90668. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90669. for (var ii = 0; ii < 3; ii++) {
  90670. var ofs = 0;
  90671. var vv = triangle.vertices[ii];
  90672. while (ofs < vCount.length) {
  90673. if (vId[ofs] === vv.id)
  90674. break;
  90675. ++ofs;
  90676. }
  90677. if (ofs === vCount.length) {
  90678. vCount.push(1);
  90679. vId.push(vv.id);
  90680. }
  90681. else {
  90682. vCount[ofs]++;
  90683. }
  90684. }
  90685. }
  90686. for (j = 0; j < vCount.length; ++j) {
  90687. if (vCount[j] === 1) {
  90688. this.vertices[vId[j]].isBorder = true;
  90689. }
  90690. else {
  90691. this.vertices[vId[j]].isBorder = false;
  90692. }
  90693. }
  90694. }
  90695. };
  90696. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90697. if (identifyBorders === void 0) { identifyBorders = false; }
  90698. var i;
  90699. if (!identifyBorders) {
  90700. var newTrianglesVector = [];
  90701. for (i = 0; i < this.triangles.length; ++i) {
  90702. if (!this.triangles[i].deleted) {
  90703. newTrianglesVector.push(this.triangles[i]);
  90704. }
  90705. }
  90706. this.triangles = newTrianglesVector;
  90707. }
  90708. for (i = 0; i < this.vertices.length; ++i) {
  90709. this.vertices[i].triangleCount = 0;
  90710. this.vertices[i].triangleStart = 0;
  90711. }
  90712. var t;
  90713. var j;
  90714. var v;
  90715. for (i = 0; i < this.triangles.length; ++i) {
  90716. t = this.triangles[i];
  90717. for (j = 0; j < 3; ++j) {
  90718. v = t.vertices[j];
  90719. v.triangleCount++;
  90720. }
  90721. }
  90722. var tStart = 0;
  90723. for (i = 0; i < this.vertices.length; ++i) {
  90724. this.vertices[i].triangleStart = tStart;
  90725. tStart += this.vertices[i].triangleCount;
  90726. this.vertices[i].triangleCount = 0;
  90727. }
  90728. var newReferences = new Array(this.triangles.length * 3);
  90729. for (i = 0; i < this.triangles.length; ++i) {
  90730. t = this.triangles[i];
  90731. for (j = 0; j < 3; ++j) {
  90732. v = t.vertices[j];
  90733. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90734. v.triangleCount++;
  90735. }
  90736. }
  90737. this.references = newReferences;
  90738. if (identifyBorders) {
  90739. this.identifyBorder();
  90740. }
  90741. };
  90742. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90743. var x = point.x;
  90744. var y = point.y;
  90745. var z = point.z;
  90746. 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
  90747. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90748. };
  90749. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90750. var q = vertex1.q.add(vertex2.q);
  90751. var border = vertex1.isBorder && vertex2.isBorder;
  90752. var error = 0;
  90753. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90754. if (qDet !== 0 && !border) {
  90755. if (!pointResult) {
  90756. pointResult = BABYLON.Vector3.Zero();
  90757. }
  90758. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90759. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90760. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90761. error = this.vertexError(q, pointResult);
  90762. }
  90763. else {
  90764. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90765. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90766. var error1 = this.vertexError(q, vertex1.position);
  90767. var error2 = this.vertexError(q, vertex2.position);
  90768. var error3 = this.vertexError(q, p3);
  90769. error = Math.min(error1, error2, error3);
  90770. if (error === error1) {
  90771. if (pointResult) {
  90772. pointResult.copyFrom(vertex1.position);
  90773. }
  90774. }
  90775. else if (error === error2) {
  90776. if (pointResult) {
  90777. pointResult.copyFrom(vertex2.position);
  90778. }
  90779. }
  90780. else {
  90781. if (pointResult) {
  90782. pointResult.copyFrom(p3);
  90783. }
  90784. }
  90785. }
  90786. return error;
  90787. };
  90788. return QuadraticErrorSimplification;
  90789. }());
  90790. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90791. })(BABYLON || (BABYLON = {}));
  90792. //# sourceMappingURL=babylon.meshSimplification.js.map
  90793. var BABYLON;
  90794. (function (BABYLON) {
  90795. var MeshLODLevel = /** @class */ (function () {
  90796. function MeshLODLevel(distance, mesh) {
  90797. this.distance = distance;
  90798. this.mesh = mesh;
  90799. }
  90800. return MeshLODLevel;
  90801. }());
  90802. BABYLON.MeshLODLevel = MeshLODLevel;
  90803. })(BABYLON || (BABYLON = {}));
  90804. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90805. var BABYLON;
  90806. (function (BABYLON) {
  90807. /**
  90808. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90809. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90810. */
  90811. var SceneOptimization = /** @class */ (function () {
  90812. /**
  90813. * Creates the SceneOptimization object
  90814. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90815. * @param desc defines the description associated with the optimization
  90816. */
  90817. function SceneOptimization(
  90818. /**
  90819. * Defines the priority of this optimization (0 by default which means first in the list)
  90820. */
  90821. priority) {
  90822. if (priority === void 0) { priority = 0; }
  90823. this.priority = priority;
  90824. }
  90825. /**
  90826. * Gets a string describing the action executed by the current optimization
  90827. * @returns description string
  90828. */
  90829. SceneOptimization.prototype.getDescription = function () {
  90830. return "";
  90831. };
  90832. /**
  90833. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90834. * @param scene defines the current scene where to apply this optimization
  90835. * @param optimizer defines the current optimizer
  90836. * @returns true if everything that can be done was applied
  90837. */
  90838. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90839. return true;
  90840. };
  90841. ;
  90842. return SceneOptimization;
  90843. }());
  90844. BABYLON.SceneOptimization = SceneOptimization;
  90845. /**
  90846. * Defines an optimization used to reduce the size of render target textures
  90847. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90848. */
  90849. var TextureOptimization = /** @class */ (function (_super) {
  90850. __extends(TextureOptimization, _super);
  90851. /**
  90852. * Creates the TextureOptimization object
  90853. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90854. * @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
  90855. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90856. */
  90857. function TextureOptimization(
  90858. /**
  90859. * Defines the priority of this optimization (0 by default which means first in the list)
  90860. */
  90861. priority,
  90862. /**
  90863. * 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
  90864. */
  90865. maximumSize,
  90866. /**
  90867. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90868. */
  90869. step) {
  90870. if (priority === void 0) { priority = 0; }
  90871. if (maximumSize === void 0) { maximumSize = 1024; }
  90872. if (step === void 0) { step = 0.5; }
  90873. var _this = _super.call(this, priority) || this;
  90874. _this.priority = priority;
  90875. _this.maximumSize = maximumSize;
  90876. _this.step = step;
  90877. return _this;
  90878. }
  90879. /**
  90880. * Gets a string describing the action executed by the current optimization
  90881. * @returns description string
  90882. */
  90883. TextureOptimization.prototype.getDescription = function () {
  90884. return "Reducing render target texture size to " + this.maximumSize;
  90885. };
  90886. /**
  90887. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90888. * @param scene defines the current scene where to apply this optimization
  90889. * @param optimizer defines the current optimizer
  90890. * @returns true if everything that can be done was applied
  90891. */
  90892. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90893. var allDone = true;
  90894. for (var index = 0; index < scene.textures.length; index++) {
  90895. var texture = scene.textures[index];
  90896. if (!texture.canRescale || texture.getContext) {
  90897. continue;
  90898. }
  90899. var currentSize = texture.getSize();
  90900. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90901. if (maxDimension > this.maximumSize) {
  90902. texture.scale(this.step);
  90903. allDone = false;
  90904. }
  90905. }
  90906. return allDone;
  90907. };
  90908. return TextureOptimization;
  90909. }(SceneOptimization));
  90910. BABYLON.TextureOptimization = TextureOptimization;
  90911. /**
  90912. * Defines an optimization used to increase or decrease the rendering resolution
  90913. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90914. */
  90915. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90916. __extends(HardwareScalingOptimization, _super);
  90917. /**
  90918. * Creates the HardwareScalingOptimization object
  90919. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90920. * @param maximumScale defines the maximum scale to use (2 by default)
  90921. * @param step defines the step to use between two passes (0.5 by default)
  90922. */
  90923. function HardwareScalingOptimization(
  90924. /**
  90925. * Defines the priority of this optimization (0 by default which means first in the list)
  90926. */
  90927. priority,
  90928. /**
  90929. * Defines the maximum scale to use (2 by default)
  90930. */
  90931. maximumScale,
  90932. /**
  90933. * Defines the step to use between two passes (0.5 by default)
  90934. */
  90935. step) {
  90936. if (priority === void 0) { priority = 0; }
  90937. if (maximumScale === void 0) { maximumScale = 2; }
  90938. if (step === void 0) { step = 0.25; }
  90939. var _this = _super.call(this, priority) || this;
  90940. _this.priority = priority;
  90941. _this.maximumScale = maximumScale;
  90942. _this.step = step;
  90943. _this._currentScale = -1;
  90944. _this._directionOffset = 1;
  90945. return _this;
  90946. }
  90947. /**
  90948. * Gets a string describing the action executed by the current optimization
  90949. * @return description string
  90950. */
  90951. HardwareScalingOptimization.prototype.getDescription = function () {
  90952. return "Setting hardware scaling level to " + this._currentScale;
  90953. };
  90954. /**
  90955. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90956. * @param scene defines the current scene where to apply this optimization
  90957. * @param optimizer defines the current optimizer
  90958. * @returns true if everything that can be done was applied
  90959. */
  90960. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90961. if (this._currentScale === -1) {
  90962. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90963. if (this._currentScale > this.maximumScale) {
  90964. this._directionOffset = -1;
  90965. }
  90966. }
  90967. this._currentScale += this._directionOffset * this.step;
  90968. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90969. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90970. };
  90971. ;
  90972. return HardwareScalingOptimization;
  90973. }(SceneOptimization));
  90974. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90975. /**
  90976. * Defines an optimization used to remove shadows
  90977. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90978. */
  90979. var ShadowsOptimization = /** @class */ (function (_super) {
  90980. __extends(ShadowsOptimization, _super);
  90981. function ShadowsOptimization() {
  90982. return _super !== null && _super.apply(this, arguments) || this;
  90983. }
  90984. /**
  90985. * Gets a string describing the action executed by the current optimization
  90986. * @return description string
  90987. */
  90988. ShadowsOptimization.prototype.getDescription = function () {
  90989. return "Turning shadows on/off";
  90990. };
  90991. /**
  90992. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90993. * @param scene defines the current scene where to apply this optimization
  90994. * @param optimizer defines the current optimizer
  90995. * @returns true if everything that can be done was applied
  90996. */
  90997. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90998. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90999. return true;
  91000. };
  91001. ;
  91002. return ShadowsOptimization;
  91003. }(SceneOptimization));
  91004. BABYLON.ShadowsOptimization = ShadowsOptimization;
  91005. /**
  91006. * Defines an optimization used to turn post-processes off
  91007. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91008. */
  91009. var PostProcessesOptimization = /** @class */ (function (_super) {
  91010. __extends(PostProcessesOptimization, _super);
  91011. function PostProcessesOptimization() {
  91012. return _super !== null && _super.apply(this, arguments) || this;
  91013. }
  91014. /**
  91015. * Gets a string describing the action executed by the current optimization
  91016. * @return description string
  91017. */
  91018. PostProcessesOptimization.prototype.getDescription = function () {
  91019. return "Turning post-processes on/off";
  91020. };
  91021. /**
  91022. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91023. * @param scene defines the current scene where to apply this optimization
  91024. * @param optimizer defines the current optimizer
  91025. * @returns true if everything that can be done was applied
  91026. */
  91027. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  91028. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  91029. return true;
  91030. };
  91031. ;
  91032. return PostProcessesOptimization;
  91033. }(SceneOptimization));
  91034. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  91035. /**
  91036. * Defines an optimization used to turn lens flares off
  91037. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91038. */
  91039. var LensFlaresOptimization = /** @class */ (function (_super) {
  91040. __extends(LensFlaresOptimization, _super);
  91041. function LensFlaresOptimization() {
  91042. return _super !== null && _super.apply(this, arguments) || this;
  91043. }
  91044. /**
  91045. * Gets a string describing the action executed by the current optimization
  91046. * @return description string
  91047. */
  91048. LensFlaresOptimization.prototype.getDescription = function () {
  91049. return "Turning lens flares on/off";
  91050. };
  91051. /**
  91052. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91053. * @param scene defines the current scene where to apply this optimization
  91054. * @param optimizer defines the current optimizer
  91055. * @returns true if everything that can be done was applied
  91056. */
  91057. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  91058. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  91059. return true;
  91060. };
  91061. ;
  91062. return LensFlaresOptimization;
  91063. }(SceneOptimization));
  91064. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  91065. /**
  91066. * Defines an optimization based on user defined callback.
  91067. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91068. */
  91069. var CustomOptimization = /** @class */ (function (_super) {
  91070. __extends(CustomOptimization, _super);
  91071. function CustomOptimization() {
  91072. return _super !== null && _super.apply(this, arguments) || this;
  91073. }
  91074. /**
  91075. * Gets a string describing the action executed by the current optimization
  91076. * @returns description string
  91077. */
  91078. CustomOptimization.prototype.getDescription = function () {
  91079. if (this.onGetDescription) {
  91080. return this.onGetDescription();
  91081. }
  91082. return "Running user defined callback";
  91083. };
  91084. /**
  91085. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91086. * @param scene defines the current scene where to apply this optimization
  91087. * @param optimizer defines the current optimizer
  91088. * @returns true if everything that can be done was applied
  91089. */
  91090. CustomOptimization.prototype.apply = function (scene, optimizer) {
  91091. if (this.onApply) {
  91092. return this.onApply(scene, optimizer);
  91093. }
  91094. return true;
  91095. };
  91096. ;
  91097. return CustomOptimization;
  91098. }(SceneOptimization));
  91099. BABYLON.CustomOptimization = CustomOptimization;
  91100. /**
  91101. * Defines an optimization used to turn particles off
  91102. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91103. */
  91104. var ParticlesOptimization = /** @class */ (function (_super) {
  91105. __extends(ParticlesOptimization, _super);
  91106. function ParticlesOptimization() {
  91107. return _super !== null && _super.apply(this, arguments) || this;
  91108. }
  91109. /**
  91110. * Gets a string describing the action executed by the current optimization
  91111. * @return description string
  91112. */
  91113. ParticlesOptimization.prototype.getDescription = function () {
  91114. return "Turning particles on/off";
  91115. };
  91116. /**
  91117. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91118. * @param scene defines the current scene where to apply this optimization
  91119. * @param optimizer defines the current optimizer
  91120. * @returns true if everything that can be done was applied
  91121. */
  91122. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  91123. scene.particlesEnabled = optimizer.isInImprovementMode;
  91124. return true;
  91125. };
  91126. ;
  91127. return ParticlesOptimization;
  91128. }(SceneOptimization));
  91129. BABYLON.ParticlesOptimization = ParticlesOptimization;
  91130. /**
  91131. * Defines an optimization used to turn render targets off
  91132. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91133. */
  91134. var RenderTargetsOptimization = /** @class */ (function (_super) {
  91135. __extends(RenderTargetsOptimization, _super);
  91136. function RenderTargetsOptimization() {
  91137. return _super !== null && _super.apply(this, arguments) || this;
  91138. }
  91139. /**
  91140. * Gets a string describing the action executed by the current optimization
  91141. * @return description string
  91142. */
  91143. RenderTargetsOptimization.prototype.getDescription = function () {
  91144. return "Turning render targets off";
  91145. };
  91146. /**
  91147. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91148. * @param scene defines the current scene where to apply this optimization
  91149. * @param optimizer defines the current optimizer
  91150. * @returns true if everything that can be done was applied
  91151. */
  91152. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  91153. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  91154. return true;
  91155. };
  91156. ;
  91157. return RenderTargetsOptimization;
  91158. }(SceneOptimization));
  91159. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  91160. /**
  91161. * Defines an optimization used to merge meshes with compatible materials
  91162. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91163. */
  91164. var MergeMeshesOptimization = /** @class */ (function (_super) {
  91165. __extends(MergeMeshesOptimization, _super);
  91166. function MergeMeshesOptimization() {
  91167. var _this = _super !== null && _super.apply(this, arguments) || this;
  91168. _this._canBeMerged = function (abstractMesh) {
  91169. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  91170. return false;
  91171. }
  91172. var mesh = abstractMesh;
  91173. if (!mesh.isVisible || !mesh.isEnabled()) {
  91174. return false;
  91175. }
  91176. if (mesh.instances.length > 0) {
  91177. return false;
  91178. }
  91179. if (mesh.skeleton || mesh.hasLODLevels) {
  91180. return false;
  91181. }
  91182. if (mesh.parent) {
  91183. return false;
  91184. }
  91185. return true;
  91186. };
  91187. return _this;
  91188. }
  91189. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  91190. /**
  91191. * Gets or sets a boolean which defines if optimization octree has to be updated
  91192. */
  91193. get: function () {
  91194. return MergeMeshesOptimization._UpdateSelectionTree;
  91195. },
  91196. /**
  91197. * Gets or sets a boolean which defines if optimization octree has to be updated
  91198. */
  91199. set: function (value) {
  91200. MergeMeshesOptimization._UpdateSelectionTree = value;
  91201. },
  91202. enumerable: true,
  91203. configurable: true
  91204. });
  91205. /**
  91206. * Gets a string describing the action executed by the current optimization
  91207. * @return description string
  91208. */
  91209. MergeMeshesOptimization.prototype.getDescription = function () {
  91210. return "Merging similar meshes together";
  91211. };
  91212. /**
  91213. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91214. * @param scene defines the current scene where to apply this optimization
  91215. * @param optimizer defines the current optimizer
  91216. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  91217. * @returns true if everything that can be done was applied
  91218. */
  91219. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  91220. var globalPool = scene.meshes.slice(0);
  91221. var globalLength = globalPool.length;
  91222. for (var index = 0; index < globalLength; index++) {
  91223. var currentPool = new Array();
  91224. var current = globalPool[index];
  91225. // Checks
  91226. if (!this._canBeMerged(current)) {
  91227. continue;
  91228. }
  91229. currentPool.push(current);
  91230. // Find compatible meshes
  91231. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  91232. var otherMesh = globalPool[subIndex];
  91233. if (!this._canBeMerged(otherMesh)) {
  91234. continue;
  91235. }
  91236. if (otherMesh.material !== current.material) {
  91237. continue;
  91238. }
  91239. if (otherMesh.checkCollisions !== current.checkCollisions) {
  91240. continue;
  91241. }
  91242. currentPool.push(otherMesh);
  91243. globalLength--;
  91244. globalPool.splice(subIndex, 1);
  91245. subIndex--;
  91246. }
  91247. if (currentPool.length < 2) {
  91248. continue;
  91249. }
  91250. // Merge meshes
  91251. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  91252. }
  91253. if (updateSelectionTree != undefined) {
  91254. if (updateSelectionTree) {
  91255. scene.createOrUpdateSelectionOctree();
  91256. }
  91257. }
  91258. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  91259. scene.createOrUpdateSelectionOctree();
  91260. }
  91261. return true;
  91262. };
  91263. ;
  91264. MergeMeshesOptimization._UpdateSelectionTree = false;
  91265. return MergeMeshesOptimization;
  91266. }(SceneOptimization));
  91267. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  91268. /**
  91269. * Defines a list of options used by SceneOptimizer
  91270. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91271. */
  91272. var SceneOptimizerOptions = /** @class */ (function () {
  91273. /**
  91274. * Creates a new list of options used by SceneOptimizer
  91275. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  91276. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  91277. */
  91278. function SceneOptimizerOptions(
  91279. /**
  91280. * Defines the target frame rate to reach (60 by default)
  91281. */
  91282. targetFrameRate,
  91283. /**
  91284. * Defines the interval between two checkes (2000ms by default)
  91285. */
  91286. trackerDuration) {
  91287. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  91288. if (trackerDuration === void 0) { trackerDuration = 2000; }
  91289. this.targetFrameRate = targetFrameRate;
  91290. this.trackerDuration = trackerDuration;
  91291. /**
  91292. * Gets the list of optimizations to apply
  91293. */
  91294. this.optimizations = new Array();
  91295. }
  91296. /**
  91297. * Add a new optimization
  91298. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  91299. * @returns the current SceneOptimizerOptions
  91300. */
  91301. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  91302. this.optimizations.push(optimization);
  91303. return this;
  91304. };
  91305. /**
  91306. * Add a new custom optimization
  91307. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  91308. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  91309. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91310. * @returns the current SceneOptimizerOptions
  91311. */
  91312. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  91313. if (priority === void 0) { priority = 0; }
  91314. var optimization = new CustomOptimization(priority);
  91315. optimization.onApply = onApply;
  91316. optimization.onGetDescription = onGetDescription;
  91317. this.optimizations.push(optimization);
  91318. return this;
  91319. };
  91320. /**
  91321. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  91322. * @param targetFrameRate defines the target frame rate (60 by default)
  91323. * @returns a SceneOptimizerOptions object
  91324. */
  91325. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  91326. var result = new SceneOptimizerOptions(targetFrameRate);
  91327. var priority = 0;
  91328. result.addOptimization(new MergeMeshesOptimization(priority));
  91329. result.addOptimization(new ShadowsOptimization(priority));
  91330. result.addOptimization(new LensFlaresOptimization(priority));
  91331. // Next priority
  91332. priority++;
  91333. result.addOptimization(new PostProcessesOptimization(priority));
  91334. result.addOptimization(new ParticlesOptimization(priority));
  91335. // Next priority
  91336. priority++;
  91337. result.addOptimization(new TextureOptimization(priority, 1024));
  91338. return result;
  91339. };
  91340. /**
  91341. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  91342. * @param targetFrameRate defines the target frame rate (60 by default)
  91343. * @returns a SceneOptimizerOptions object
  91344. */
  91345. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  91346. var result = new SceneOptimizerOptions(targetFrameRate);
  91347. var priority = 0;
  91348. result.addOptimization(new MergeMeshesOptimization(priority));
  91349. result.addOptimization(new ShadowsOptimization(priority));
  91350. result.addOptimization(new LensFlaresOptimization(priority));
  91351. // Next priority
  91352. priority++;
  91353. result.addOptimization(new PostProcessesOptimization(priority));
  91354. result.addOptimization(new ParticlesOptimization(priority));
  91355. // Next priority
  91356. priority++;
  91357. result.addOptimization(new TextureOptimization(priority, 512));
  91358. // Next priority
  91359. priority++;
  91360. result.addOptimization(new RenderTargetsOptimization(priority));
  91361. // Next priority
  91362. priority++;
  91363. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91364. return result;
  91365. };
  91366. /**
  91367. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91368. * @param targetFrameRate defines the target frame rate (60 by default)
  91369. * @returns a SceneOptimizerOptions object
  91370. */
  91371. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91372. var result = new SceneOptimizerOptions(targetFrameRate);
  91373. var priority = 0;
  91374. result.addOptimization(new MergeMeshesOptimization(priority));
  91375. result.addOptimization(new ShadowsOptimization(priority));
  91376. result.addOptimization(new LensFlaresOptimization(priority));
  91377. // Next priority
  91378. priority++;
  91379. result.addOptimization(new PostProcessesOptimization(priority));
  91380. result.addOptimization(new ParticlesOptimization(priority));
  91381. // Next priority
  91382. priority++;
  91383. result.addOptimization(new TextureOptimization(priority, 256));
  91384. // Next priority
  91385. priority++;
  91386. result.addOptimization(new RenderTargetsOptimization(priority));
  91387. // Next priority
  91388. priority++;
  91389. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91390. return result;
  91391. };
  91392. return SceneOptimizerOptions;
  91393. }());
  91394. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91395. /**
  91396. * Class used to run optimizations in order to reach a target frame rate
  91397. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91398. */
  91399. var SceneOptimizer = /** @class */ (function () {
  91400. /**
  91401. * Creates a new SceneOptimizer
  91402. * @param scene defines the scene to work on
  91403. * @param options defines the options to use with the SceneOptimizer
  91404. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91405. * @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)
  91406. */
  91407. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91408. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91409. if (improvementMode === void 0) { improvementMode = false; }
  91410. var _this = this;
  91411. this._isRunning = false;
  91412. this._currentPriorityLevel = 0;
  91413. this._targetFrameRate = 60;
  91414. this._trackerDuration = 2000;
  91415. this._currentFrameRate = 0;
  91416. this._improvementMode = false;
  91417. /**
  91418. * Defines an observable called when the optimizer reaches the target frame rate
  91419. */
  91420. this.onSuccessObservable = new BABYLON.Observable();
  91421. /**
  91422. * Defines an observable called when the optimizer enables an optimization
  91423. */
  91424. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91425. /**
  91426. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91427. */
  91428. this.onFailureObservable = new BABYLON.Observable();
  91429. if (!options) {
  91430. this._options = new SceneOptimizerOptions();
  91431. }
  91432. else {
  91433. this._options = options;
  91434. }
  91435. if (this._options.targetFrameRate) {
  91436. this._targetFrameRate = this._options.targetFrameRate;
  91437. }
  91438. if (this._options.trackerDuration) {
  91439. this._trackerDuration = this._options.trackerDuration;
  91440. }
  91441. if (autoGeneratePriorities) {
  91442. var priority = 0;
  91443. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91444. var optim = _a[_i];
  91445. optim.priority = priority++;
  91446. }
  91447. }
  91448. this._improvementMode = improvementMode;
  91449. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91450. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91451. _this._sceneDisposeObserver = null;
  91452. _this.dispose();
  91453. });
  91454. }
  91455. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91456. /**
  91457. * Gets a boolean indicating if the optimizer is in improvement mode
  91458. */
  91459. get: function () {
  91460. return this._improvementMode;
  91461. },
  91462. enumerable: true,
  91463. configurable: true
  91464. });
  91465. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91466. /**
  91467. * Gets the current priority level (0 at start)
  91468. */
  91469. get: function () {
  91470. return this._currentPriorityLevel;
  91471. },
  91472. enumerable: true,
  91473. configurable: true
  91474. });
  91475. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91476. /**
  91477. * Gets the current frame rate checked by the SceneOptimizer
  91478. */
  91479. get: function () {
  91480. return this._currentFrameRate;
  91481. },
  91482. enumerable: true,
  91483. configurable: true
  91484. });
  91485. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91486. /**
  91487. * Gets or sets the current target frame rate (60 by default)
  91488. */
  91489. get: function () {
  91490. return this._targetFrameRate;
  91491. },
  91492. /**
  91493. * Gets or sets the current target frame rate (60 by default)
  91494. */
  91495. set: function (value) {
  91496. this._targetFrameRate = value;
  91497. },
  91498. enumerable: true,
  91499. configurable: true
  91500. });
  91501. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91502. /**
  91503. * Gets or sets the current interval between two checks (every 2000ms by default)
  91504. */
  91505. get: function () {
  91506. return this._trackerDuration;
  91507. },
  91508. /**
  91509. * Gets or sets the current interval between two checks (every 2000ms by default)
  91510. */
  91511. set: function (value) {
  91512. this._trackerDuration = value;
  91513. },
  91514. enumerable: true,
  91515. configurable: true
  91516. });
  91517. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91518. /**
  91519. * Gets the list of active optimizations
  91520. */
  91521. get: function () {
  91522. return this._options.optimizations;
  91523. },
  91524. enumerable: true,
  91525. configurable: true
  91526. });
  91527. /**
  91528. * Stops the current optimizer
  91529. */
  91530. SceneOptimizer.prototype.stop = function () {
  91531. this._isRunning = false;
  91532. };
  91533. /**
  91534. * Reset the optimizer to initial step (current priority level = 0)
  91535. */
  91536. SceneOptimizer.prototype.reset = function () {
  91537. this._currentPriorityLevel = 0;
  91538. };
  91539. /**
  91540. * Start the optimizer. By default it will try to reach a specific framerate
  91541. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91542. */
  91543. SceneOptimizer.prototype.start = function () {
  91544. var _this = this;
  91545. if (this._isRunning) {
  91546. return;
  91547. }
  91548. this._isRunning = true;
  91549. // Let's wait for the scene to be ready before running our check
  91550. this._scene.executeWhenReady(function () {
  91551. setTimeout(function () {
  91552. _this._checkCurrentState();
  91553. }, _this._trackerDuration);
  91554. });
  91555. };
  91556. SceneOptimizer.prototype._checkCurrentState = function () {
  91557. var _this = this;
  91558. if (!this._isRunning) {
  91559. return;
  91560. }
  91561. var scene = this._scene;
  91562. var options = this._options;
  91563. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91564. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91565. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91566. this._isRunning = false;
  91567. this.onSuccessObservable.notifyObservers(this);
  91568. return;
  91569. }
  91570. // Apply current level of optimizations
  91571. var allDone = true;
  91572. var noOptimizationApplied = true;
  91573. for (var index = 0; index < options.optimizations.length; index++) {
  91574. var optimization = options.optimizations[index];
  91575. if (optimization.priority === this._currentPriorityLevel) {
  91576. noOptimizationApplied = false;
  91577. allDone = allDone && optimization.apply(scene, this);
  91578. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91579. }
  91580. }
  91581. // If no optimization was applied, this is a failure :(
  91582. if (noOptimizationApplied) {
  91583. this._isRunning = false;
  91584. this.onFailureObservable.notifyObservers(this);
  91585. return;
  91586. }
  91587. // If all optimizations were done, move to next level
  91588. if (allDone) {
  91589. this._currentPriorityLevel++;
  91590. }
  91591. // Let's the system running for a specific amount of time before checking FPS
  91592. scene.executeWhenReady(function () {
  91593. setTimeout(function () {
  91594. _this._checkCurrentState();
  91595. }, _this._trackerDuration);
  91596. });
  91597. };
  91598. /**
  91599. * Release all resources
  91600. */
  91601. SceneOptimizer.prototype.dispose = function () {
  91602. this.stop();
  91603. this.onSuccessObservable.clear();
  91604. this.onFailureObservable.clear();
  91605. this.onNewOptimizationAppliedObservable.clear();
  91606. if (this._sceneDisposeObserver) {
  91607. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91608. }
  91609. };
  91610. /**
  91611. * Helper function to create a SceneOptimizer with one single line of code
  91612. * @param scene defines the scene to work on
  91613. * @param options defines the options to use with the SceneOptimizer
  91614. * @param onSuccess defines a callback to call on success
  91615. * @param onFailure defines a callback to call on failure
  91616. * @returns the new SceneOptimizer object
  91617. */
  91618. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91619. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91620. if (onSuccess) {
  91621. optimizer.onSuccessObservable.add(function () {
  91622. onSuccess();
  91623. });
  91624. }
  91625. if (onFailure) {
  91626. optimizer.onFailureObservable.add(function () {
  91627. onFailure();
  91628. });
  91629. }
  91630. optimizer.start();
  91631. return optimizer;
  91632. };
  91633. return SceneOptimizer;
  91634. }());
  91635. BABYLON.SceneOptimizer = SceneOptimizer;
  91636. })(BABYLON || (BABYLON = {}));
  91637. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91638. var BABYLON;
  91639. (function (BABYLON) {
  91640. var OutlineRenderer = /** @class */ (function () {
  91641. function OutlineRenderer(scene) {
  91642. this.zOffset = 1;
  91643. this._scene = scene;
  91644. }
  91645. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91646. var _this = this;
  91647. if (useOverlay === void 0) { useOverlay = false; }
  91648. var scene = this._scene;
  91649. var engine = this._scene.getEngine();
  91650. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91651. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91652. return;
  91653. }
  91654. var mesh = subMesh.getRenderingMesh();
  91655. var material = subMesh.getMaterial();
  91656. if (!material || !scene.activeCamera) {
  91657. return;
  91658. }
  91659. engine.enableEffect(this._effect);
  91660. // Logarithmic depth
  91661. if (material.useLogarithmicDepth) {
  91662. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91663. }
  91664. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91665. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91666. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91667. // Bones
  91668. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91669. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91670. }
  91671. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91672. // Alpha test
  91673. if (material && material.needAlphaTesting()) {
  91674. var alphaTexture = material.getAlphaTestTexture();
  91675. if (alphaTexture) {
  91676. this._effect.setTexture("diffuseSampler", alphaTexture);
  91677. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91678. }
  91679. }
  91680. engine.setZOffset(-this.zOffset);
  91681. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91682. engine.setZOffset(0);
  91683. };
  91684. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91685. var defines = [];
  91686. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91687. var mesh = subMesh.getMesh();
  91688. var material = subMesh.getMaterial();
  91689. if (material) {
  91690. // Alpha test
  91691. if (material.needAlphaTesting()) {
  91692. defines.push("#define ALPHATEST");
  91693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91694. attribs.push(BABYLON.VertexBuffer.UVKind);
  91695. defines.push("#define UV1");
  91696. }
  91697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91698. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91699. defines.push("#define UV2");
  91700. }
  91701. }
  91702. //Logarithmic depth
  91703. if (material.useLogarithmicDepth) {
  91704. defines.push("#define LOGARITHMICDEPTH");
  91705. }
  91706. }
  91707. // Bones
  91708. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91709. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91710. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91711. if (mesh.numBoneInfluencers > 4) {
  91712. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91713. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91714. }
  91715. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91716. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91717. }
  91718. else {
  91719. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91720. }
  91721. // Instances
  91722. if (useInstances) {
  91723. defines.push("#define INSTANCES");
  91724. attribs.push("world0");
  91725. attribs.push("world1");
  91726. attribs.push("world2");
  91727. attribs.push("world3");
  91728. }
  91729. // Get correct effect
  91730. var join = defines.join("\n");
  91731. if (this._cachedDefines !== join) {
  91732. this._cachedDefines = join;
  91733. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91734. }
  91735. return this._effect.isReady();
  91736. };
  91737. return OutlineRenderer;
  91738. }());
  91739. BABYLON.OutlineRenderer = OutlineRenderer;
  91740. })(BABYLON || (BABYLON = {}));
  91741. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91742. var BABYLON;
  91743. (function (BABYLON) {
  91744. var FaceAdjacencies = /** @class */ (function () {
  91745. function FaceAdjacencies() {
  91746. this.edges = new Array();
  91747. this.edgesConnectedCount = 0;
  91748. }
  91749. return FaceAdjacencies;
  91750. }());
  91751. var EdgesRenderer = /** @class */ (function () {
  91752. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91753. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91754. if (epsilon === void 0) { epsilon = 0.95; }
  91755. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91756. this.edgesWidthScalerForOrthographic = 1000.0;
  91757. this.edgesWidthScalerForPerspective = 50.0;
  91758. this._linesPositions = new Array();
  91759. this._linesNormals = new Array();
  91760. this._linesIndices = new Array();
  91761. this._buffers = {};
  91762. this._checkVerticesInsteadOfIndices = false;
  91763. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  91764. this.isEnabled = true;
  91765. this._source = source;
  91766. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91767. this._epsilon = epsilon;
  91768. this._prepareRessources();
  91769. this._generateEdgesLines();
  91770. }
  91771. EdgesRenderer.prototype._prepareRessources = function () {
  91772. if (this._lineShader) {
  91773. return;
  91774. }
  91775. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91776. attributes: ["position", "normal"],
  91777. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91778. });
  91779. this._lineShader.disableDepthWrite = true;
  91780. this._lineShader.backFaceCulling = false;
  91781. };
  91782. EdgesRenderer.prototype._rebuild = function () {
  91783. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91784. if (buffer) {
  91785. buffer._rebuild();
  91786. }
  91787. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91788. if (buffer) {
  91789. buffer._rebuild();
  91790. }
  91791. var scene = this._source.getScene();
  91792. var engine = scene.getEngine();
  91793. this._ib = engine.createIndexBuffer(this._linesIndices);
  91794. };
  91795. EdgesRenderer.prototype.dispose = function () {
  91796. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91797. if (buffer) {
  91798. buffer.dispose();
  91799. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91800. }
  91801. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91802. if (buffer) {
  91803. buffer.dispose();
  91804. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91805. }
  91806. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91807. this._lineShader.dispose();
  91808. };
  91809. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91810. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91811. return 0;
  91812. }
  91813. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91814. return 1;
  91815. }
  91816. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91817. return 2;
  91818. }
  91819. return -1;
  91820. };
  91821. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91822. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91823. return 0;
  91824. }
  91825. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91826. return 1;
  91827. }
  91828. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91829. return 2;
  91830. }
  91831. return -1;
  91832. };
  91833. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91834. var needToCreateLine;
  91835. if (edge === undefined) {
  91836. needToCreateLine = true;
  91837. }
  91838. else {
  91839. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91840. needToCreateLine = dotProduct < this._epsilon;
  91841. }
  91842. if (needToCreateLine) {
  91843. var offset = this._linesPositions.length / 3;
  91844. var normal = p0.subtract(p1);
  91845. normal.normalize();
  91846. // Positions
  91847. this._linesPositions.push(p0.x);
  91848. this._linesPositions.push(p0.y);
  91849. this._linesPositions.push(p0.z);
  91850. this._linesPositions.push(p0.x);
  91851. this._linesPositions.push(p0.y);
  91852. this._linesPositions.push(p0.z);
  91853. this._linesPositions.push(p1.x);
  91854. this._linesPositions.push(p1.y);
  91855. this._linesPositions.push(p1.z);
  91856. this._linesPositions.push(p1.x);
  91857. this._linesPositions.push(p1.y);
  91858. this._linesPositions.push(p1.z);
  91859. // Normals
  91860. this._linesNormals.push(p1.x);
  91861. this._linesNormals.push(p1.y);
  91862. this._linesNormals.push(p1.z);
  91863. this._linesNormals.push(-1);
  91864. this._linesNormals.push(p1.x);
  91865. this._linesNormals.push(p1.y);
  91866. this._linesNormals.push(p1.z);
  91867. this._linesNormals.push(1);
  91868. this._linesNormals.push(p0.x);
  91869. this._linesNormals.push(p0.y);
  91870. this._linesNormals.push(p0.z);
  91871. this._linesNormals.push(-1);
  91872. this._linesNormals.push(p0.x);
  91873. this._linesNormals.push(p0.y);
  91874. this._linesNormals.push(p0.z);
  91875. this._linesNormals.push(1);
  91876. // Indices
  91877. this._linesIndices.push(offset);
  91878. this._linesIndices.push(offset + 1);
  91879. this._linesIndices.push(offset + 2);
  91880. this._linesIndices.push(offset);
  91881. this._linesIndices.push(offset + 2);
  91882. this._linesIndices.push(offset + 3);
  91883. }
  91884. };
  91885. EdgesRenderer.prototype._generateEdgesLines = function () {
  91886. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91887. var indices = this._source.getIndices();
  91888. if (!indices || !positions) {
  91889. return;
  91890. }
  91891. // First let's find adjacencies
  91892. var adjacencies = new Array();
  91893. var faceNormals = new Array();
  91894. var index;
  91895. var faceAdjacencies;
  91896. // Prepare faces
  91897. for (index = 0; index < indices.length; index += 3) {
  91898. faceAdjacencies = new FaceAdjacencies();
  91899. var p0Index = indices[index];
  91900. var p1Index = indices[index + 1];
  91901. var p2Index = indices[index + 2];
  91902. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91903. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91904. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91905. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91906. faceNormal.normalize();
  91907. faceNormals.push(faceNormal);
  91908. adjacencies.push(faceAdjacencies);
  91909. }
  91910. // Scan
  91911. for (index = 0; index < adjacencies.length; index++) {
  91912. faceAdjacencies = adjacencies[index];
  91913. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91914. var otherFaceAdjacencies = adjacencies[otherIndex];
  91915. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91916. break;
  91917. }
  91918. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91919. continue;
  91920. }
  91921. var otherP0 = indices[otherIndex * 3];
  91922. var otherP1 = indices[otherIndex * 3 + 1];
  91923. var otherP2 = indices[otherIndex * 3 + 2];
  91924. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91925. var otherEdgeIndex = 0;
  91926. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91927. continue;
  91928. }
  91929. switch (edgeIndex) {
  91930. case 0:
  91931. if (this._checkVerticesInsteadOfIndices) {
  91932. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91933. }
  91934. else {
  91935. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91936. }
  91937. break;
  91938. case 1:
  91939. if (this._checkVerticesInsteadOfIndices) {
  91940. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91941. }
  91942. else {
  91943. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91944. }
  91945. break;
  91946. case 2:
  91947. if (this._checkVerticesInsteadOfIndices) {
  91948. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91949. }
  91950. else {
  91951. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91952. }
  91953. break;
  91954. }
  91955. if (otherEdgeIndex === -1) {
  91956. continue;
  91957. }
  91958. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91959. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91960. faceAdjacencies.edgesConnectedCount++;
  91961. otherFaceAdjacencies.edgesConnectedCount++;
  91962. if (faceAdjacencies.edgesConnectedCount === 3) {
  91963. break;
  91964. }
  91965. }
  91966. }
  91967. }
  91968. // Create lines
  91969. for (index = 0; index < adjacencies.length; index++) {
  91970. // 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
  91971. var current = adjacencies[index];
  91972. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91973. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91974. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91975. }
  91976. // Merge into a single mesh
  91977. var engine = this._source.getScene().getEngine();
  91978. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91979. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91980. this._ib = engine.createIndexBuffer(this._linesIndices);
  91981. this._indicesCount = this._linesIndices.length;
  91982. };
  91983. EdgesRenderer.prototype.render = function () {
  91984. var scene = this._source.getScene();
  91985. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91986. return;
  91987. }
  91988. var engine = scene.getEngine();
  91989. this._lineShader._preBind();
  91990. // VBOs
  91991. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91992. scene.resetCachedMaterial();
  91993. this._lineShader.setColor4("color", this._source.edgesColor);
  91994. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91995. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91996. }
  91997. else {
  91998. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91999. }
  92000. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  92001. this._lineShader.bind(this._source.getWorldMatrix());
  92002. // Draw order
  92003. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  92004. this._lineShader.unbind();
  92005. engine.setDepthWrite(true);
  92006. };
  92007. return EdgesRenderer;
  92008. }());
  92009. BABYLON.EdgesRenderer = EdgesRenderer;
  92010. })(BABYLON || (BABYLON = {}));
  92011. //# sourceMappingURL=babylon.edgesRenderer.js.map
  92012. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92013. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92014. s = arguments[i];
  92015. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92016. t[p] = s[p];
  92017. }
  92018. return t;
  92019. };
  92020. var BABYLON;
  92021. (function (BABYLON) {
  92022. /**
  92023. * The effect layer Helps adding post process effect blended with the main pass.
  92024. *
  92025. * This can be for instance use to generate glow or higlight effects on the scene.
  92026. *
  92027. * The effect layer class can not be used directly and is intented to inherited from to be
  92028. * customized per effects.
  92029. */
  92030. var EffectLayer = /** @class */ (function () {
  92031. /**
  92032. * Instantiates a new effect Layer and references it in the scene.
  92033. * @param name The name of the layer
  92034. * @param scene The scene to use the layer in
  92035. */
  92036. function EffectLayer(
  92037. /** The Friendly of the effect in the scene */
  92038. name, scene) {
  92039. this._vertexBuffers = {};
  92040. this._maxSize = 0;
  92041. this._mainTextureDesiredSize = { width: 0, height: 0 };
  92042. this._shouldRender = true;
  92043. this._postProcesses = [];
  92044. this._textures = [];
  92045. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  92046. /**
  92047. * The clear color of the texture used to generate the glow map.
  92048. */
  92049. this.neutralColor = new BABYLON.Color4();
  92050. /**
  92051. * Specifies wether the highlight layer is enabled or not.
  92052. */
  92053. this.isEnabled = true;
  92054. /**
  92055. * An event triggered when the effect layer has been disposed.
  92056. */
  92057. this.onDisposeObservable = new BABYLON.Observable();
  92058. /**
  92059. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  92060. */
  92061. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  92062. /**
  92063. * An event triggered when the generated texture is being merged in the scene.
  92064. */
  92065. this.onBeforeComposeObservable = new BABYLON.Observable();
  92066. /**
  92067. * An event triggered when the generated texture has been merged in the scene.
  92068. */
  92069. this.onAfterComposeObservable = new BABYLON.Observable();
  92070. /**
  92071. * An event triggered when the efffect layer changes its size.
  92072. */
  92073. this.onSizeChangedObservable = new BABYLON.Observable();
  92074. this.name = name;
  92075. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92076. this._engine = scene.getEngine();
  92077. this._maxSize = this._engine.getCaps().maxTextureSize;
  92078. this._scene.effectLayers.push(this);
  92079. // Generate Buffers
  92080. this._generateIndexBuffer();
  92081. this._genrateVertexBuffer();
  92082. }
  92083. Object.defineProperty(EffectLayer.prototype, "camera", {
  92084. /**
  92085. * Gets the camera attached to the layer.
  92086. */
  92087. get: function () {
  92088. return this._effectLayerOptions.camera;
  92089. },
  92090. enumerable: true,
  92091. configurable: true
  92092. });
  92093. /**
  92094. * Initializes the effect layer with the required options.
  92095. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  92096. */
  92097. EffectLayer.prototype._init = function (options) {
  92098. // Adapt options
  92099. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92100. this._setMainTextureSize();
  92101. this._createMainTexture();
  92102. this._createTextureAndPostProcesses();
  92103. this._mergeEffect = this._createMergeEffect();
  92104. };
  92105. /**
  92106. * Generates the index buffer of the full screen quad blending to the main canvas.
  92107. */
  92108. EffectLayer.prototype._generateIndexBuffer = function () {
  92109. // Indices
  92110. var indices = [];
  92111. indices.push(0);
  92112. indices.push(1);
  92113. indices.push(2);
  92114. indices.push(0);
  92115. indices.push(2);
  92116. indices.push(3);
  92117. this._indexBuffer = this._engine.createIndexBuffer(indices);
  92118. };
  92119. /**
  92120. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  92121. */
  92122. EffectLayer.prototype._genrateVertexBuffer = function () {
  92123. // VBO
  92124. var vertices = [];
  92125. vertices.push(1, 1);
  92126. vertices.push(-1, 1);
  92127. vertices.push(-1, -1);
  92128. vertices.push(1, -1);
  92129. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92130. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92131. };
  92132. /**
  92133. * Sets the main texture desired size which is the closest power of two
  92134. * of the engine canvas size.
  92135. */
  92136. EffectLayer.prototype._setMainTextureSize = function () {
  92137. if (this._effectLayerOptions.mainTextureFixedSize) {
  92138. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  92139. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  92140. }
  92141. else {
  92142. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  92143. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  92144. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  92145. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  92146. }
  92147. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  92148. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  92149. };
  92150. /**
  92151. * Creates the main texture for the effect layer.
  92152. */
  92153. EffectLayer.prototype._createMainTexture = function () {
  92154. var _this = this;
  92155. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  92156. width: this._mainTextureDesiredSize.width,
  92157. height: this._mainTextureDesiredSize.height
  92158. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92159. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  92160. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92161. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92162. this._mainTexture.anisotropicFilteringLevel = 1;
  92163. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92164. this._mainTexture.renderParticles = false;
  92165. this._mainTexture.renderList = null;
  92166. this._mainTexture.ignoreCameraViewport = true;
  92167. // Custom render function
  92168. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  92169. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  92170. var index;
  92171. var engine = _this._scene.getEngine();
  92172. if (depthOnlySubMeshes.length) {
  92173. engine.setColorWrite(false);
  92174. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  92175. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  92176. }
  92177. engine.setColorWrite(true);
  92178. }
  92179. for (index = 0; index < opaqueSubMeshes.length; index++) {
  92180. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  92181. }
  92182. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  92183. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  92184. }
  92185. for (index = 0; index < transparentSubMeshes.length; index++) {
  92186. _this._renderSubMesh(transparentSubMeshes.data[index]);
  92187. }
  92188. };
  92189. this._mainTexture.onClearObservable.add(function (engine) {
  92190. engine.clear(_this.neutralColor, true, true, true);
  92191. });
  92192. };
  92193. /**
  92194. * Checks for the readiness of the element composing the layer.
  92195. * @param subMesh the mesh to check for
  92196. * @param useInstances specify wether or not to use instances to render the mesh
  92197. * @param emissiveTexture the associated emissive texture used to generate the glow
  92198. * @return true if ready otherwise, false
  92199. */
  92200. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  92201. var material = subMesh.getMaterial();
  92202. if (!material) {
  92203. return false;
  92204. }
  92205. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  92206. return false;
  92207. }
  92208. var defines = [];
  92209. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92210. var mesh = subMesh.getMesh();
  92211. var uv1 = false;
  92212. var uv2 = false;
  92213. // Alpha test
  92214. if (material && material.needAlphaTesting()) {
  92215. var alphaTexture = material.getAlphaTestTexture();
  92216. if (alphaTexture) {
  92217. defines.push("#define ALPHATEST");
  92218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92219. alphaTexture.coordinatesIndex === 1) {
  92220. defines.push("#define DIFFUSEUV2");
  92221. uv2 = true;
  92222. }
  92223. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92224. defines.push("#define DIFFUSEUV1");
  92225. uv1 = true;
  92226. }
  92227. }
  92228. }
  92229. // Emissive
  92230. if (emissiveTexture) {
  92231. defines.push("#define EMISSIVE");
  92232. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92233. emissiveTexture.coordinatesIndex === 1) {
  92234. defines.push("#define EMISSIVEUV2");
  92235. uv2 = true;
  92236. }
  92237. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92238. defines.push("#define EMISSIVEUV1");
  92239. uv1 = true;
  92240. }
  92241. }
  92242. if (uv1) {
  92243. attribs.push(BABYLON.VertexBuffer.UVKind);
  92244. defines.push("#define UV1");
  92245. }
  92246. if (uv2) {
  92247. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92248. defines.push("#define UV2");
  92249. }
  92250. // Bones
  92251. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92252. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92253. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92254. if (mesh.numBoneInfluencers > 4) {
  92255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92257. }
  92258. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92259. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  92260. }
  92261. else {
  92262. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92263. }
  92264. // Morph targets
  92265. var manager = mesh.morphTargetManager;
  92266. var morphInfluencers = 0;
  92267. if (manager) {
  92268. if (manager.numInfluencers > 0) {
  92269. defines.push("#define MORPHTARGETS");
  92270. morphInfluencers = manager.numInfluencers;
  92271. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  92272. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  92273. }
  92274. }
  92275. // Instances
  92276. if (useInstances) {
  92277. defines.push("#define INSTANCES");
  92278. attribs.push("world0");
  92279. attribs.push("world1");
  92280. attribs.push("world2");
  92281. attribs.push("world3");
  92282. }
  92283. // Get correct effect
  92284. var join = defines.join("\n");
  92285. if (this._cachedDefines !== join) {
  92286. this._cachedDefines = join;
  92287. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  92288. }
  92289. return this._effectLayerMapGenerationEffect.isReady();
  92290. };
  92291. /**
  92292. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  92293. */
  92294. EffectLayer.prototype.render = function () {
  92295. var currentEffect = this._mergeEffect;
  92296. // Check
  92297. if (!currentEffect.isReady())
  92298. return;
  92299. for (var i = 0; i < this._postProcesses.length; i++) {
  92300. if (!this._postProcesses[i].isReady()) {
  92301. return;
  92302. }
  92303. }
  92304. var engine = this._scene.getEngine();
  92305. this.onBeforeComposeObservable.notifyObservers(this);
  92306. // Render
  92307. engine.enableEffect(currentEffect);
  92308. engine.setState(false);
  92309. // VBOs
  92310. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92311. // Cache
  92312. var previousAlphaMode = engine.getAlphaMode();
  92313. // Go Blend.
  92314. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  92315. // Blends the map on the main canvas.
  92316. this._internalRender(currentEffect);
  92317. // Restore Alpha
  92318. engine.setAlphaMode(previousAlphaMode);
  92319. this.onAfterComposeObservable.notifyObservers(this);
  92320. // Handle size changes.
  92321. var size = this._mainTexture.getSize();
  92322. this._setMainTextureSize();
  92323. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  92324. // Recreate RTT and post processes on size change.
  92325. this.onSizeChangedObservable.notifyObservers(this);
  92326. this._disposeTextureAndPostProcesses();
  92327. this._createMainTexture();
  92328. this._createTextureAndPostProcesses();
  92329. }
  92330. };
  92331. /**
  92332. * Determine if a given mesh will be used in the current effect.
  92333. * @param mesh mesh to test
  92334. * @returns true if the mesh will be used
  92335. */
  92336. EffectLayer.prototype.hasMesh = function (mesh) {
  92337. return true;
  92338. };
  92339. /**
  92340. * Returns true if the layer contains information to display, otherwise false.
  92341. * @returns true if the glow layer should be rendered
  92342. */
  92343. EffectLayer.prototype.shouldRender = function () {
  92344. return this.isEnabled && this._shouldRender;
  92345. };
  92346. /**
  92347. * Returns true if the mesh should render, otherwise false.
  92348. * @param mesh The mesh to render
  92349. * @returns true if it should render otherwise false
  92350. */
  92351. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  92352. return true;
  92353. };
  92354. /**
  92355. * Returns true if the mesh should render, otherwise false.
  92356. * @param mesh The mesh to render
  92357. * @returns true if it should render otherwise false
  92358. */
  92359. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  92360. return true;
  92361. };
  92362. /**
  92363. * Renders the submesh passed in parameter to the generation map.
  92364. */
  92365. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92366. var _this = this;
  92367. if (!this.shouldRender()) {
  92368. return;
  92369. }
  92370. var material = subMesh.getMaterial();
  92371. var mesh = subMesh.getRenderingMesh();
  92372. var scene = this._scene;
  92373. var engine = scene.getEngine();
  92374. if (!material) {
  92375. return;
  92376. }
  92377. // Do not block in blend mode.
  92378. if (material.needAlphaBlendingForMesh(mesh)) {
  92379. return;
  92380. }
  92381. // Culling
  92382. engine.setState(material.backFaceCulling);
  92383. // Managing instances
  92384. var batch = mesh._getInstancesRenderList(subMesh._id);
  92385. if (batch.mustReturn) {
  92386. return;
  92387. }
  92388. // Early Exit per mesh
  92389. if (!this._shouldRenderMesh(mesh)) {
  92390. return;
  92391. }
  92392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92393. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92394. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92395. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92396. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92397. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92398. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92399. // Alpha test
  92400. if (material && material.needAlphaTesting()) {
  92401. var alphaTexture = material.getAlphaTestTexture();
  92402. if (alphaTexture) {
  92403. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92404. var textureMatrix = alphaTexture.getTextureMatrix();
  92405. if (textureMatrix) {
  92406. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92407. }
  92408. }
  92409. }
  92410. // Glow emissive only
  92411. if (this._emissiveTextureAndColor.texture) {
  92412. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92413. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92414. }
  92415. // Bones
  92416. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92417. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92418. }
  92419. // Morph targets
  92420. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92421. // Draw
  92422. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92423. }
  92424. else {
  92425. // Need to reset refresh rate of the shadowMap
  92426. this._mainTexture.resetRefreshCounter();
  92427. }
  92428. };
  92429. /**
  92430. * Rebuild the required buffers.
  92431. * @hidden Internal use only.
  92432. */
  92433. EffectLayer.prototype._rebuild = function () {
  92434. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92435. if (vb) {
  92436. vb._rebuild();
  92437. }
  92438. this._generateIndexBuffer();
  92439. };
  92440. /**
  92441. * Dispose only the render target textures and post process.
  92442. */
  92443. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92444. this._mainTexture.dispose();
  92445. for (var i = 0; i < this._postProcesses.length; i++) {
  92446. if (this._postProcesses[i]) {
  92447. this._postProcesses[i].dispose();
  92448. }
  92449. }
  92450. this._postProcesses = [];
  92451. for (var i = 0; i < this._textures.length; i++) {
  92452. if (this._textures[i]) {
  92453. this._textures[i].dispose();
  92454. }
  92455. }
  92456. this._textures = [];
  92457. };
  92458. /**
  92459. * Dispose the highlight layer and free resources.
  92460. */
  92461. EffectLayer.prototype.dispose = function () {
  92462. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92463. if (vertexBuffer) {
  92464. vertexBuffer.dispose();
  92465. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92466. }
  92467. if (this._indexBuffer) {
  92468. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92469. this._indexBuffer = null;
  92470. }
  92471. // Clean textures and post processes
  92472. this._disposeTextureAndPostProcesses();
  92473. // Remove from scene
  92474. var index = this._scene.effectLayers.indexOf(this, 0);
  92475. if (index > -1) {
  92476. this._scene.effectLayers.splice(index, 1);
  92477. }
  92478. // Callback
  92479. this.onDisposeObservable.notifyObservers(this);
  92480. this.onDisposeObservable.clear();
  92481. this.onBeforeRenderMainTextureObservable.clear();
  92482. this.onBeforeComposeObservable.clear();
  92483. this.onAfterComposeObservable.clear();
  92484. this.onSizeChangedObservable.clear();
  92485. };
  92486. /**
  92487. * Gets the class name of the effect layer
  92488. * @returns the string with the class name of the effect layer
  92489. */
  92490. EffectLayer.prototype.getClassName = function () {
  92491. return "EffectLayer";
  92492. };
  92493. /**
  92494. * Creates an effect layer from parsed effect layer data
  92495. * @param parsedEffectLayer defines effect layer data
  92496. * @param scene defines the current scene
  92497. * @param rootUrl defines the root URL containing the effect layer information
  92498. * @returns a parsed effect Layer
  92499. */
  92500. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92501. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92502. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92503. };
  92504. __decorate([
  92505. BABYLON.serialize()
  92506. ], EffectLayer.prototype, "name", void 0);
  92507. __decorate([
  92508. BABYLON.serializeAsColor4()
  92509. ], EffectLayer.prototype, "neutralColor", void 0);
  92510. __decorate([
  92511. BABYLON.serialize()
  92512. ], EffectLayer.prototype, "isEnabled", void 0);
  92513. __decorate([
  92514. BABYLON.serializeAsCameraReference()
  92515. ], EffectLayer.prototype, "camera", null);
  92516. return EffectLayer;
  92517. }());
  92518. BABYLON.EffectLayer = EffectLayer;
  92519. })(BABYLON || (BABYLON = {}));
  92520. //# sourceMappingURL=babylon.effectLayer.js.map
  92521. var BABYLON;
  92522. (function (BABYLON) {
  92523. /**
  92524. * Special Glow Blur post process only blurring the alpha channel
  92525. * It enforces keeping the most luminous color in the color channel.
  92526. */
  92527. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92528. __extends(GlowBlurPostProcess, _super);
  92529. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92531. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92532. _this.direction = direction;
  92533. _this.kernel = kernel;
  92534. _this.onApplyObservable.add(function (effect) {
  92535. effect.setFloat2("screenSize", _this.width, _this.height);
  92536. effect.setVector2("direction", _this.direction);
  92537. effect.setFloat("blurWidth", _this.kernel);
  92538. });
  92539. return _this;
  92540. }
  92541. return GlowBlurPostProcess;
  92542. }(BABYLON.PostProcess));
  92543. /**
  92544. * The highlight layer Helps adding a glow effect around a mesh.
  92545. *
  92546. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92547. * glowy meshes to your scene.
  92548. *
  92549. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92550. */
  92551. var HighlightLayer = /** @class */ (function (_super) {
  92552. __extends(HighlightLayer, _super);
  92553. /**
  92554. * Instantiates a new highlight Layer and references it to the scene..
  92555. * @param name The name of the layer
  92556. * @param scene The scene to use the layer in
  92557. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92558. */
  92559. function HighlightLayer(name, scene, options) {
  92560. var _this = _super.call(this, name, scene) || this;
  92561. _this.name = name;
  92562. /**
  92563. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92564. */
  92565. _this.innerGlow = true;
  92566. /**
  92567. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92568. */
  92569. _this.outerGlow = true;
  92570. /**
  92571. * An event triggered when the highlight layer is being blurred.
  92572. */
  92573. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92574. /**
  92575. * An event triggered when the highlight layer has been blurred.
  92576. */
  92577. _this.onAfterBlurObservable = new BABYLON.Observable();
  92578. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92579. _this._meshes = {};
  92580. _this._excludedMeshes = {};
  92581. _this.neutralColor = HighlightLayer.NeutralColor;
  92582. // Warn on stencil
  92583. if (!_this._engine.isStencilEnable) {
  92584. 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 }");
  92585. }
  92586. // Adapt options
  92587. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92588. // Initialize the layer
  92589. _this._init({
  92590. alphaBlendingMode: _this._options.alphaBlendingMode,
  92591. camera: _this._options.camera,
  92592. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92593. mainTextureRatio: _this._options.mainTextureRatio
  92594. });
  92595. // Do not render as long as no meshes have been added
  92596. _this._shouldRender = false;
  92597. return _this;
  92598. }
  92599. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92600. /**
  92601. * Gets the horizontal size of the blur.
  92602. */
  92603. get: function () {
  92604. return this._horizontalBlurPostprocess.kernel;
  92605. },
  92606. /**
  92607. * Specifies the horizontal size of the blur.
  92608. */
  92609. set: function (value) {
  92610. this._horizontalBlurPostprocess.kernel = value;
  92611. },
  92612. enumerable: true,
  92613. configurable: true
  92614. });
  92615. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92616. /**
  92617. * Gets the vertical size of the blur.
  92618. */
  92619. get: function () {
  92620. return this._verticalBlurPostprocess.kernel;
  92621. },
  92622. /**
  92623. * Specifies the vertical size of the blur.
  92624. */
  92625. set: function (value) {
  92626. this._verticalBlurPostprocess.kernel = value;
  92627. },
  92628. enumerable: true,
  92629. configurable: true
  92630. });
  92631. /**
  92632. * Get the effect name of the layer.
  92633. * @return The effect name
  92634. */
  92635. HighlightLayer.prototype.getEffectName = function () {
  92636. return HighlightLayer.EffectName;
  92637. };
  92638. /**
  92639. * Create the merge effect. This is the shader use to blit the information back
  92640. * to the main canvas at the end of the scene rendering.
  92641. */
  92642. HighlightLayer.prototype._createMergeEffect = function () {
  92643. // Effect
  92644. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92645. };
  92646. /**
  92647. * Creates the render target textures and post processes used in the highlight layer.
  92648. */
  92649. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92650. var _this = this;
  92651. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92652. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92653. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92654. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92655. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92656. width: blurTextureWidth,
  92657. height: blurTextureHeight
  92658. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92659. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92660. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92661. this._blurTexture.anisotropicFilteringLevel = 16;
  92662. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92663. this._blurTexture.renderParticles = false;
  92664. this._blurTexture.ignoreCameraViewport = true;
  92665. this._textures = [this._blurTexture];
  92666. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92667. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92668. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92669. effect.setTexture("textureSampler", _this._mainTexture);
  92670. });
  92671. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92672. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92673. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92674. });
  92675. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92676. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92677. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92678. });
  92679. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92680. }
  92681. else {
  92682. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92683. width: blurTextureWidth,
  92684. height: blurTextureHeight
  92685. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92686. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92687. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92688. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92689. effect.setTexture("textureSampler", _this._mainTexture);
  92690. });
  92691. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92692. width: blurTextureWidth,
  92693. height: blurTextureHeight
  92694. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92695. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92696. }
  92697. this._mainTexture.onAfterUnbindObservable.add(function () {
  92698. _this.onBeforeBlurObservable.notifyObservers(_this);
  92699. var internalTexture = _this._blurTexture.getInternalTexture();
  92700. if (internalTexture) {
  92701. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92702. }
  92703. _this.onAfterBlurObservable.notifyObservers(_this);
  92704. });
  92705. // Prevent autoClear.
  92706. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92707. };
  92708. /**
  92709. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92710. */
  92711. HighlightLayer.prototype.needStencil = function () {
  92712. return true;
  92713. };
  92714. /**
  92715. * Checks for the readiness of the element composing the layer.
  92716. * @param subMesh the mesh to check for
  92717. * @param useInstances specify wether or not to use instances to render the mesh
  92718. * @param emissiveTexture the associated emissive texture used to generate the glow
  92719. * @return true if ready otherwise, false
  92720. */
  92721. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92722. var material = subMesh.getMaterial();
  92723. var mesh = subMesh.getRenderingMesh();
  92724. if (!material || !mesh || !this._meshes) {
  92725. return false;
  92726. }
  92727. var emissiveTexture = null;
  92728. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92729. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92730. emissiveTexture = material.emissiveTexture;
  92731. }
  92732. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92733. };
  92734. /**
  92735. * Implementation specific of rendering the generating effect on the main canvas.
  92736. * @param effect The effect used to render through
  92737. */
  92738. HighlightLayer.prototype._internalRender = function (effect) {
  92739. // Texture
  92740. effect.setTexture("textureSampler", this._blurTexture);
  92741. // Cache
  92742. var engine = this._engine;
  92743. var previousStencilBuffer = engine.getStencilBuffer();
  92744. var previousStencilFunction = engine.getStencilFunction();
  92745. var previousStencilMask = engine.getStencilMask();
  92746. var previousStencilOperationPass = engine.getStencilOperationPass();
  92747. var previousStencilOperationFail = engine.getStencilOperationFail();
  92748. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92749. var previousStencilReference = engine.getStencilFunctionReference();
  92750. // Stencil operations
  92751. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92752. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92753. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92754. // Draw order
  92755. engine.setStencilMask(0x00);
  92756. engine.setStencilBuffer(true);
  92757. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92758. // 2 passes inner outer
  92759. if (this.outerGlow) {
  92760. effect.setFloat("offset", 0);
  92761. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92762. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92763. }
  92764. if (this.innerGlow) {
  92765. effect.setFloat("offset", 1);
  92766. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92767. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92768. }
  92769. // Restore Cache
  92770. engine.setStencilFunction(previousStencilFunction);
  92771. engine.setStencilMask(previousStencilMask);
  92772. engine.setStencilBuffer(previousStencilBuffer);
  92773. engine.setStencilOperationPass(previousStencilOperationPass);
  92774. engine.setStencilOperationFail(previousStencilOperationFail);
  92775. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92776. engine.setStencilFunctionReference(previousStencilReference);
  92777. };
  92778. /**
  92779. * Returns true if the layer contains information to display, otherwise false.
  92780. */
  92781. HighlightLayer.prototype.shouldRender = function () {
  92782. if (_super.prototype.shouldRender.call(this)) {
  92783. return this._meshes ? true : false;
  92784. }
  92785. return false;
  92786. };
  92787. /**
  92788. * Returns true if the mesh should render, otherwise false.
  92789. * @param mesh The mesh to render
  92790. * @returns true if it should render otherwise false
  92791. */
  92792. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92793. // Excluded Mesh
  92794. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92795. return false;
  92796. }
  92797. ;
  92798. return true;
  92799. };
  92800. /**
  92801. * Sets the required values for both the emissive texture and and the main color.
  92802. */
  92803. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92804. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92805. if (highlightLayerMesh) {
  92806. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92807. }
  92808. else {
  92809. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92810. }
  92811. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92812. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92813. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92814. }
  92815. else {
  92816. this._emissiveTextureAndColor.texture = null;
  92817. }
  92818. };
  92819. /**
  92820. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92821. * @param mesh The mesh to exclude from the highlight layer
  92822. */
  92823. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92824. if (!this._excludedMeshes) {
  92825. return;
  92826. }
  92827. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92828. if (!meshExcluded) {
  92829. this._excludedMeshes[mesh.uniqueId] = {
  92830. mesh: mesh,
  92831. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92832. mesh.getEngine().setStencilBuffer(false);
  92833. }),
  92834. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92835. mesh.getEngine().setStencilBuffer(true);
  92836. }),
  92837. };
  92838. }
  92839. };
  92840. /**
  92841. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92842. * @param mesh The mesh to highlight
  92843. */
  92844. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92845. if (!this._excludedMeshes) {
  92846. return;
  92847. }
  92848. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92849. if (meshExcluded) {
  92850. if (meshExcluded.beforeRender) {
  92851. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92852. }
  92853. if (meshExcluded.afterRender) {
  92854. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92855. }
  92856. }
  92857. this._excludedMeshes[mesh.uniqueId] = null;
  92858. };
  92859. /**
  92860. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92861. * @param mesh mesh to test
  92862. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92863. */
  92864. HighlightLayer.prototype.hasMesh = function (mesh) {
  92865. if (!this._meshes) {
  92866. return false;
  92867. }
  92868. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92869. };
  92870. /**
  92871. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92872. * @param mesh The mesh to highlight
  92873. * @param color The color of the highlight
  92874. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92875. */
  92876. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92877. var _this = this;
  92878. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92879. if (!this._meshes) {
  92880. return;
  92881. }
  92882. var meshHighlight = this._meshes[mesh.uniqueId];
  92883. if (meshHighlight) {
  92884. meshHighlight.color = color;
  92885. }
  92886. else {
  92887. this._meshes[mesh.uniqueId] = {
  92888. mesh: mesh,
  92889. color: color,
  92890. // Lambda required for capture due to Observable this context
  92891. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92892. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92893. _this._defaultStencilReference(mesh);
  92894. }
  92895. else {
  92896. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92897. }
  92898. }),
  92899. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92900. glowEmissiveOnly: glowEmissiveOnly
  92901. };
  92902. }
  92903. this._shouldRender = true;
  92904. };
  92905. /**
  92906. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92907. * @param mesh The mesh to highlight
  92908. */
  92909. HighlightLayer.prototype.removeMesh = function (mesh) {
  92910. if (!this._meshes) {
  92911. return;
  92912. }
  92913. var meshHighlight = this._meshes[mesh.uniqueId];
  92914. if (meshHighlight) {
  92915. if (meshHighlight.observerHighlight) {
  92916. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92917. }
  92918. if (meshHighlight.observerDefault) {
  92919. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92920. }
  92921. delete this._meshes[mesh.uniqueId];
  92922. }
  92923. this._shouldRender = false;
  92924. for (var meshHighlightToCheck in this._meshes) {
  92925. if (this._meshes[meshHighlightToCheck]) {
  92926. this._shouldRender = true;
  92927. break;
  92928. }
  92929. }
  92930. };
  92931. /**
  92932. * Force the stencil to the normal expected value for none glowing parts
  92933. */
  92934. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92935. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92936. };
  92937. /**
  92938. * Free any resources and references associated to a mesh.
  92939. * Internal use
  92940. * @param mesh The mesh to free.
  92941. */
  92942. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92943. this.removeMesh(mesh);
  92944. this.removeExcludedMesh(mesh);
  92945. };
  92946. /**
  92947. * Dispose the highlight layer and free resources.
  92948. */
  92949. HighlightLayer.prototype.dispose = function () {
  92950. if (this._meshes) {
  92951. // Clean mesh references
  92952. for (var id in this._meshes) {
  92953. var meshHighlight = this._meshes[id];
  92954. if (meshHighlight && meshHighlight.mesh) {
  92955. if (meshHighlight.observerHighlight) {
  92956. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92957. }
  92958. if (meshHighlight.observerDefault) {
  92959. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92960. }
  92961. }
  92962. }
  92963. this._meshes = null;
  92964. }
  92965. if (this._excludedMeshes) {
  92966. for (var id in this._excludedMeshes) {
  92967. var meshHighlight = this._excludedMeshes[id];
  92968. if (meshHighlight) {
  92969. if (meshHighlight.beforeRender) {
  92970. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92971. }
  92972. if (meshHighlight.afterRender) {
  92973. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92974. }
  92975. }
  92976. }
  92977. this._excludedMeshes = null;
  92978. }
  92979. _super.prototype.dispose.call(this);
  92980. };
  92981. /**
  92982. * Gets the class name of the effect layer
  92983. * @returns the string with the class name of the effect layer
  92984. */
  92985. HighlightLayer.prototype.getClassName = function () {
  92986. return "HighlightLayer";
  92987. };
  92988. /**
  92989. * Serializes this Highlight layer
  92990. * @returns a serialized Highlight layer object
  92991. */
  92992. HighlightLayer.prototype.serialize = function () {
  92993. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92994. serializationObject.customType = "BABYLON.HighlightLayer";
  92995. // Highlighted meshes
  92996. serializationObject.meshes = [];
  92997. if (this._meshes) {
  92998. for (var m in this._meshes) {
  92999. var mesh = this._meshes[m];
  93000. if (mesh) {
  93001. serializationObject.meshes.push({
  93002. glowEmissiveOnly: mesh.glowEmissiveOnly,
  93003. color: mesh.color.asArray(),
  93004. meshId: mesh.mesh.id
  93005. });
  93006. }
  93007. }
  93008. }
  93009. // Excluded meshes
  93010. serializationObject.excludedMeshes = [];
  93011. if (this._excludedMeshes) {
  93012. for (var e in this._excludedMeshes) {
  93013. var excludedMesh = this._excludedMeshes[e];
  93014. if (excludedMesh) {
  93015. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  93016. }
  93017. }
  93018. }
  93019. return serializationObject;
  93020. };
  93021. /**
  93022. * Creates a Highlight layer from parsed Highlight layer data
  93023. * @param parsedHightlightLayer defines the Highlight layer data
  93024. * @param scene defines the current scene
  93025. * @param rootUrl defines the root URL containing the Highlight layer information
  93026. * @returns a parsed Highlight layer
  93027. */
  93028. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  93029. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  93030. var index;
  93031. // Excluded meshes
  93032. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  93033. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  93034. if (mesh) {
  93035. hl.addExcludedMesh(mesh);
  93036. }
  93037. }
  93038. // Included meshes
  93039. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  93040. var highlightedMesh = parsedHightlightLayer.meshes[index];
  93041. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  93042. if (mesh) {
  93043. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  93044. }
  93045. }
  93046. return hl;
  93047. };
  93048. /**
  93049. * Effect Name of the highlight layer.
  93050. */
  93051. HighlightLayer.EffectName = "HighlightLayer";
  93052. /**
  93053. * The neutral color used during the preparation of the glow effect.
  93054. * This is black by default as the blend operation is a blend operation.
  93055. */
  93056. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  93057. /**
  93058. * Stencil value used for glowing meshes.
  93059. */
  93060. HighlightLayer.GlowingMeshStencilReference = 0x02;
  93061. /**
  93062. * Stencil value used for the other meshes in the scene.
  93063. */
  93064. HighlightLayer.NormalMeshStencilReference = 0x01;
  93065. __decorate([
  93066. BABYLON.serialize()
  93067. ], HighlightLayer.prototype, "innerGlow", void 0);
  93068. __decorate([
  93069. BABYLON.serialize()
  93070. ], HighlightLayer.prototype, "outerGlow", void 0);
  93071. __decorate([
  93072. BABYLON.serialize()
  93073. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  93074. __decorate([
  93075. BABYLON.serialize()
  93076. ], HighlightLayer.prototype, "blurVerticalSize", null);
  93077. __decorate([
  93078. BABYLON.serialize("options")
  93079. ], HighlightLayer.prototype, "_options", void 0);
  93080. return HighlightLayer;
  93081. }(BABYLON.EffectLayer));
  93082. BABYLON.HighlightLayer = HighlightLayer;
  93083. })(BABYLON || (BABYLON = {}));
  93084. //# sourceMappingURL=babylon.highlightLayer.js.map
  93085. var BABYLON;
  93086. (function (BABYLON) {
  93087. /**
  93088. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  93089. *
  93090. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93091. * glowy meshes to your scene.
  93092. *
  93093. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  93094. */
  93095. var GlowLayer = /** @class */ (function (_super) {
  93096. __extends(GlowLayer, _super);
  93097. /**
  93098. * Instantiates a new glow Layer and references it to the scene.
  93099. * @param name The name of the layer
  93100. * @param scene The scene to use the layer in
  93101. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  93102. */
  93103. function GlowLayer(name, scene, options) {
  93104. var _this = _super.call(this, name, scene) || this;
  93105. _this._intensity = 1.0;
  93106. _this._includedOnlyMeshes = [];
  93107. _this._excludedMeshes = [];
  93108. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  93109. // Adapt options
  93110. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  93111. // Initialize the layer
  93112. _this._init({
  93113. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  93114. camera: _this._options.camera,
  93115. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93116. mainTextureRatio: _this._options.mainTextureRatio
  93117. });
  93118. return _this;
  93119. }
  93120. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  93121. /**
  93122. * Gets the kernel size of the blur.
  93123. */
  93124. get: function () {
  93125. return this._horizontalBlurPostprocess1.kernel;
  93126. },
  93127. /**
  93128. * Sets the kernel size of the blur.
  93129. */
  93130. set: function (value) {
  93131. this._horizontalBlurPostprocess1.kernel = value;
  93132. this._verticalBlurPostprocess1.kernel = value;
  93133. this._horizontalBlurPostprocess2.kernel = value;
  93134. this._verticalBlurPostprocess2.kernel = value;
  93135. },
  93136. enumerable: true,
  93137. configurable: true
  93138. });
  93139. Object.defineProperty(GlowLayer.prototype, "intensity", {
  93140. /**
  93141. * Gets the glow intensity.
  93142. */
  93143. get: function () {
  93144. return this._intensity;
  93145. },
  93146. /**
  93147. * Sets the glow intensity.
  93148. */
  93149. set: function (value) {
  93150. this._intensity = value;
  93151. },
  93152. enumerable: true,
  93153. configurable: true
  93154. });
  93155. /**
  93156. * Get the effect name of the layer.
  93157. * @return The effect name
  93158. */
  93159. GlowLayer.prototype.getEffectName = function () {
  93160. return GlowLayer.EffectName;
  93161. };
  93162. /**
  93163. * Create the merge effect. This is the shader use to blit the information back
  93164. * to the main canvas at the end of the scene rendering.
  93165. */
  93166. GlowLayer.prototype._createMergeEffect = function () {
  93167. // Effect
  93168. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  93169. };
  93170. /**
  93171. * Creates the render target textures and post processes used in the glow layer.
  93172. */
  93173. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  93174. var _this = this;
  93175. var blurTextureWidth = this._mainTextureDesiredSize.width;
  93176. var blurTextureHeight = this._mainTextureDesiredSize.height;
  93177. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93178. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93179. var textureType = 0;
  93180. if (this._engine.getCaps().textureHalfFloatRender) {
  93181. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93182. }
  93183. else {
  93184. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93185. }
  93186. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  93187. width: blurTextureWidth,
  93188. height: blurTextureHeight
  93189. }, this._scene, false, true, textureType);
  93190. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93191. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93192. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93193. this._blurTexture1.renderParticles = false;
  93194. this._blurTexture1.ignoreCameraViewport = true;
  93195. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  93196. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  93197. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  93198. width: blurTextureWidth2,
  93199. height: blurTextureHeight2
  93200. }, this._scene, false, true, textureType);
  93201. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93202. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93203. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93204. this._blurTexture2.renderParticles = false;
  93205. this._blurTexture2.ignoreCameraViewport = true;
  93206. this._textures = [this._blurTexture1, this._blurTexture2];
  93207. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93208. width: blurTextureWidth,
  93209. height: blurTextureHeight
  93210. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93211. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  93212. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  93213. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  93214. effect.setTexture("textureSampler", _this._mainTexture);
  93215. });
  93216. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93217. width: blurTextureWidth,
  93218. height: blurTextureHeight
  93219. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93220. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93221. width: blurTextureWidth2,
  93222. height: blurTextureHeight2
  93223. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93224. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  93225. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  93226. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  93227. effect.setTexture("textureSampler", _this._blurTexture1);
  93228. });
  93229. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93230. width: blurTextureWidth2,
  93231. height: blurTextureHeight2
  93232. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93233. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93234. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  93235. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93236. this._mainTexture.samples = this._options.mainTextureSamples;
  93237. this._mainTexture.onAfterUnbindObservable.add(function () {
  93238. var internalTexture = _this._blurTexture1.getInternalTexture();
  93239. if (internalTexture) {
  93240. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  93241. internalTexture = _this._blurTexture2.getInternalTexture();
  93242. if (internalTexture) {
  93243. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  93244. }
  93245. }
  93246. });
  93247. // Prevent autoClear.
  93248. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93249. };
  93250. /**
  93251. * Checks for the readiness of the element composing the layer.
  93252. * @param subMesh the mesh to check for
  93253. * @param useInstances specify wether or not to use instances to render the mesh
  93254. * @param emissiveTexture the associated emissive texture used to generate the glow
  93255. * @return true if ready otherwise, false
  93256. */
  93257. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  93258. var material = subMesh.getMaterial();
  93259. var mesh = subMesh.getRenderingMesh();
  93260. if (!material || !mesh) {
  93261. return false;
  93262. }
  93263. var emissiveTexture = material.emissiveTexture;
  93264. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93265. };
  93266. /**
  93267. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93268. */
  93269. GlowLayer.prototype.needStencil = function () {
  93270. return false;
  93271. };
  93272. /**
  93273. * Implementation specific of rendering the generating effect on the main canvas.
  93274. * @param effect The effect used to render through
  93275. */
  93276. GlowLayer.prototype._internalRender = function (effect) {
  93277. // Texture
  93278. effect.setTexture("textureSampler", this._blurTexture1);
  93279. effect.setTexture("textureSampler2", this._blurTexture2);
  93280. effect.setFloat("offset", this._intensity);
  93281. // Cache
  93282. var engine = this._engine;
  93283. var previousStencilBuffer = engine.getStencilBuffer();
  93284. // Draw order
  93285. engine.setStencilBuffer(false);
  93286. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93287. // Draw order
  93288. engine.setStencilBuffer(previousStencilBuffer);
  93289. };
  93290. /**
  93291. * Sets the required values for both the emissive texture and and the main color.
  93292. */
  93293. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93294. var textureLevel = 1.0;
  93295. if (this.customEmissiveTextureSelector) {
  93296. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  93297. }
  93298. else {
  93299. if (material) {
  93300. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93301. if (this._emissiveTextureAndColor.texture) {
  93302. textureLevel = this._emissiveTextureAndColor.texture.level;
  93303. }
  93304. }
  93305. else {
  93306. this._emissiveTextureAndColor.texture = null;
  93307. }
  93308. }
  93309. if (this.customEmissiveColorSelector) {
  93310. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  93311. }
  93312. else {
  93313. if (material.emissiveColor) {
  93314. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  93315. }
  93316. else {
  93317. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93318. }
  93319. }
  93320. };
  93321. /**
  93322. * Returns true if the mesh should render, otherwise false.
  93323. * @param mesh The mesh to render
  93324. * @returns true if it should render otherwise false
  93325. */
  93326. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  93327. return this.hasMesh(mesh);
  93328. };
  93329. /**
  93330. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  93331. * @param mesh The mesh to exclude from the glow layer
  93332. */
  93333. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  93334. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  93335. this._excludedMeshes.push(mesh.uniqueId);
  93336. }
  93337. };
  93338. /**
  93339. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  93340. * @param mesh The mesh to remove
  93341. */
  93342. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  93343. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  93344. if (index !== -1) {
  93345. this._excludedMeshes.splice(index, 1);
  93346. }
  93347. };
  93348. /**
  93349. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  93350. * @param mesh The mesh to include in the glow layer
  93351. */
  93352. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  93353. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  93354. this._includedOnlyMeshes.push(mesh.uniqueId);
  93355. }
  93356. };
  93357. /**
  93358. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  93359. * @param mesh The mesh to remove
  93360. */
  93361. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  93362. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93363. if (index !== -1) {
  93364. this._includedOnlyMeshes.splice(index, 1);
  93365. }
  93366. };
  93367. /**
  93368. * Determine if a given mesh will be used in the glow layer
  93369. * @param mesh The mesh to test
  93370. * @returns true if the mesh will be highlighted by the current glow layer
  93371. */
  93372. GlowLayer.prototype.hasMesh = function (mesh) {
  93373. // Included Mesh
  93374. if (this._includedOnlyMeshes.length) {
  93375. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93376. }
  93377. ;
  93378. // Excluded Mesh
  93379. if (this._excludedMeshes.length) {
  93380. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93381. }
  93382. ;
  93383. return true;
  93384. };
  93385. /**
  93386. * Free any resources and references associated to a mesh.
  93387. * Internal use
  93388. * @param mesh The mesh to free.
  93389. */
  93390. GlowLayer.prototype._disposeMesh = function (mesh) {
  93391. this.removeIncludedOnlyMesh(mesh);
  93392. this.removeExcludedMesh(mesh);
  93393. };
  93394. /**
  93395. * Gets the class name of the effect layer
  93396. * @returns the string with the class name of the effect layer
  93397. */
  93398. GlowLayer.prototype.getClassName = function () {
  93399. return "GlowLayer";
  93400. };
  93401. /**
  93402. * Serializes this glow layer
  93403. * @returns a serialized glow layer object
  93404. */
  93405. GlowLayer.prototype.serialize = function () {
  93406. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93407. serializationObject.customType = "BABYLON.GlowLayer";
  93408. var index;
  93409. // Included meshes
  93410. serializationObject.includedMeshes = [];
  93411. if (this._includedOnlyMeshes.length) {
  93412. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93413. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93414. if (mesh) {
  93415. serializationObject.includedMeshes.push(mesh.id);
  93416. }
  93417. }
  93418. }
  93419. // Excluded meshes
  93420. serializationObject.excludedMeshes = [];
  93421. if (this._excludedMeshes.length) {
  93422. for (index = 0; index < this._excludedMeshes.length; index++) {
  93423. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93424. if (mesh) {
  93425. serializationObject.excludedMeshes.push(mesh.id);
  93426. }
  93427. }
  93428. }
  93429. return serializationObject;
  93430. };
  93431. /**
  93432. * Creates a Glow Layer from parsed glow layer data
  93433. * @param parsedGlowLayer defines glow layer data
  93434. * @param scene defines the current scene
  93435. * @param rootUrl defines the root URL containing the glow layer information
  93436. * @returns a parsed Glow Layer
  93437. */
  93438. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93439. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93440. var index;
  93441. // Excluded meshes
  93442. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93443. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93444. if (mesh) {
  93445. gl.addExcludedMesh(mesh);
  93446. }
  93447. }
  93448. // Included meshes
  93449. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93450. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93451. if (mesh) {
  93452. gl.addIncludedOnlyMesh(mesh);
  93453. }
  93454. }
  93455. return gl;
  93456. };
  93457. /**
  93458. * Effect Name of the layer.
  93459. */
  93460. GlowLayer.EffectName = "GlowLayer";
  93461. /**
  93462. * The default blur kernel size used for the glow.
  93463. */
  93464. GlowLayer.DefaultBlurKernelSize = 32;
  93465. /**
  93466. * The default texture size ratio used for the glow.
  93467. */
  93468. GlowLayer.DefaultTextureRatio = 0.5;
  93469. __decorate([
  93470. BABYLON.serialize()
  93471. ], GlowLayer.prototype, "blurKernelSize", null);
  93472. __decorate([
  93473. BABYLON.serialize()
  93474. ], GlowLayer.prototype, "intensity", null);
  93475. __decorate([
  93476. BABYLON.serialize("options")
  93477. ], GlowLayer.prototype, "_options", void 0);
  93478. return GlowLayer;
  93479. }(BABYLON.EffectLayer));
  93480. BABYLON.GlowLayer = GlowLayer;
  93481. })(BABYLON || (BABYLON = {}));
  93482. //# sourceMappingURL=babylon.glowLayer.js.map
  93483. var BABYLON;
  93484. (function (BABYLON) {
  93485. /**
  93486. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93487. */
  93488. var AssetTaskState;
  93489. (function (AssetTaskState) {
  93490. /**
  93491. * Initialization
  93492. */
  93493. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93494. /**
  93495. * Running
  93496. */
  93497. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93498. /**
  93499. * Done
  93500. */
  93501. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93502. /**
  93503. * Error
  93504. */
  93505. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93506. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93507. /**
  93508. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93509. */
  93510. var AbstractAssetTask = /** @class */ (function () {
  93511. /**
  93512. * Creates a new {BABYLON.AssetsManager}
  93513. * @param name defines the name of the task
  93514. */
  93515. function AbstractAssetTask(
  93516. /**
  93517. * Task name
  93518. */ name) {
  93519. this.name = name;
  93520. this._isCompleted = false;
  93521. this._taskState = AssetTaskState.INIT;
  93522. }
  93523. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93524. /**
  93525. * Get if the task is completed
  93526. */
  93527. get: function () {
  93528. return this._isCompleted;
  93529. },
  93530. enumerable: true,
  93531. configurable: true
  93532. });
  93533. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93534. /**
  93535. * Gets the current state of the task
  93536. */
  93537. get: function () {
  93538. return this._taskState;
  93539. },
  93540. enumerable: true,
  93541. configurable: true
  93542. });
  93543. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93544. /**
  93545. * Gets the current error object (if task is in error)
  93546. */
  93547. get: function () {
  93548. return this._errorObject;
  93549. },
  93550. enumerable: true,
  93551. configurable: true
  93552. });
  93553. /**
  93554. * Internal only
  93555. * @hidden
  93556. */
  93557. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93558. if (this._errorObject) {
  93559. return;
  93560. }
  93561. this._errorObject = {
  93562. message: message,
  93563. exception: exception
  93564. };
  93565. };
  93566. /**
  93567. * Execute the current task
  93568. * @param scene defines the scene where you want your assets to be loaded
  93569. * @param onSuccess is a callback called when the task is successfully executed
  93570. * @param onError is a callback called if an error occurs
  93571. */
  93572. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93573. var _this = this;
  93574. this._taskState = AssetTaskState.RUNNING;
  93575. this.runTask(scene, function () {
  93576. _this.onDoneCallback(onSuccess, onError);
  93577. }, function (msg, exception) {
  93578. _this.onErrorCallback(onError, msg, exception);
  93579. });
  93580. };
  93581. /**
  93582. * Execute the current task
  93583. * @param scene defines the scene where you want your assets to be loaded
  93584. * @param onSuccess is a callback called when the task is successfully executed
  93585. * @param onError is a callback called if an error occurs
  93586. */
  93587. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93588. throw new Error("runTask is not implemented");
  93589. };
  93590. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93591. this._taskState = AssetTaskState.ERROR;
  93592. this._errorObject = {
  93593. message: message,
  93594. exception: exception
  93595. };
  93596. if (this.onError) {
  93597. this.onError(this, message, exception);
  93598. }
  93599. onError();
  93600. };
  93601. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93602. try {
  93603. this._taskState = AssetTaskState.DONE;
  93604. this._isCompleted = true;
  93605. if (this.onSuccess) {
  93606. this.onSuccess(this);
  93607. }
  93608. onSuccess();
  93609. }
  93610. catch (e) {
  93611. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93612. }
  93613. };
  93614. return AbstractAssetTask;
  93615. }());
  93616. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93617. /**
  93618. * Class used to share progress information about assets loading
  93619. */
  93620. var AssetsProgressEvent = /** @class */ (function () {
  93621. /**
  93622. * Creates a {BABYLON.AssetsProgressEvent}
  93623. * @param remainingCount defines the number of remaining tasks to process
  93624. * @param totalCount defines the total number of tasks
  93625. * @param task defines the task that was just processed
  93626. */
  93627. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93628. this.remainingCount = remainingCount;
  93629. this.totalCount = totalCount;
  93630. this.task = task;
  93631. }
  93632. return AssetsProgressEvent;
  93633. }());
  93634. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93635. /**
  93636. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93637. */
  93638. var MeshAssetTask = /** @class */ (function (_super) {
  93639. __extends(MeshAssetTask, _super);
  93640. /**
  93641. * Creates a new {BABYLON.MeshAssetTask}
  93642. * @param name defines the name of the task
  93643. * @param meshesNames defines the list of mesh's names you want to load
  93644. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93645. * @param sceneFilename defines the filename of the scene to load from
  93646. */
  93647. function MeshAssetTask(
  93648. /**
  93649. * Defines the name of the task
  93650. */
  93651. name,
  93652. /**
  93653. * Defines the list of mesh's names you want to load
  93654. */
  93655. meshesNames,
  93656. /**
  93657. * Defines the root url to use as a base to load your meshes and associated resources
  93658. */
  93659. rootUrl,
  93660. /**
  93661. * Defines the filename of the scene to load from
  93662. */
  93663. sceneFilename) {
  93664. var _this = _super.call(this, name) || this;
  93665. _this.name = name;
  93666. _this.meshesNames = meshesNames;
  93667. _this.rootUrl = rootUrl;
  93668. _this.sceneFilename = sceneFilename;
  93669. return _this;
  93670. }
  93671. /**
  93672. * Execute the current task
  93673. * @param scene defines the scene where you want your assets to be loaded
  93674. * @param onSuccess is a callback called when the task is successfully executed
  93675. * @param onError is a callback called if an error occurs
  93676. */
  93677. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93678. var _this = this;
  93679. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93680. _this.loadedMeshes = meshes;
  93681. _this.loadedParticleSystems = particleSystems;
  93682. _this.loadedSkeletons = skeletons;
  93683. onSuccess();
  93684. }, null, function (scene, message, exception) {
  93685. onError(message, exception);
  93686. });
  93687. };
  93688. return MeshAssetTask;
  93689. }(AbstractAssetTask));
  93690. BABYLON.MeshAssetTask = MeshAssetTask;
  93691. /**
  93692. * Define a task used by {BABYLON.AssetsManager} to load text content
  93693. */
  93694. var TextFileAssetTask = /** @class */ (function (_super) {
  93695. __extends(TextFileAssetTask, _super);
  93696. /**
  93697. * Creates a new TextFileAssetTask object
  93698. * @param name defines the name of the task
  93699. * @param url defines the location of the file to load
  93700. */
  93701. function TextFileAssetTask(
  93702. /**
  93703. * Defines the name of the task
  93704. */
  93705. name,
  93706. /**
  93707. * Defines the location of the file to load
  93708. */
  93709. url) {
  93710. var _this = _super.call(this, name) || this;
  93711. _this.name = name;
  93712. _this.url = url;
  93713. return _this;
  93714. }
  93715. /**
  93716. * Execute the current task
  93717. * @param scene defines the scene where you want your assets to be loaded
  93718. * @param onSuccess is a callback called when the task is successfully executed
  93719. * @param onError is a callback called if an error occurs
  93720. */
  93721. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93722. var _this = this;
  93723. scene._loadFile(this.url, function (data) {
  93724. _this.text = data;
  93725. onSuccess();
  93726. }, undefined, false, false, function (request, exception) {
  93727. if (request) {
  93728. onError(request.status + " " + request.statusText, exception);
  93729. }
  93730. });
  93731. };
  93732. return TextFileAssetTask;
  93733. }(AbstractAssetTask));
  93734. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93735. /**
  93736. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93737. */
  93738. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93739. __extends(BinaryFileAssetTask, _super);
  93740. /**
  93741. * Creates a new BinaryFileAssetTask object
  93742. * @param name defines the name of the new task
  93743. * @param url defines the location of the file to load
  93744. */
  93745. function BinaryFileAssetTask(
  93746. /**
  93747. * Defines the name of the task
  93748. */
  93749. name,
  93750. /**
  93751. * Defines the location of the file to load
  93752. */
  93753. url) {
  93754. var _this = _super.call(this, name) || this;
  93755. _this.name = name;
  93756. _this.url = url;
  93757. return _this;
  93758. }
  93759. /**
  93760. * Execute the current task
  93761. * @param scene defines the scene where you want your assets to be loaded
  93762. * @param onSuccess is a callback called when the task is successfully executed
  93763. * @param onError is a callback called if an error occurs
  93764. */
  93765. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93766. var _this = this;
  93767. scene._loadFile(this.url, function (data) {
  93768. _this.data = data;
  93769. onSuccess();
  93770. }, undefined, true, true, function (request, exception) {
  93771. if (request) {
  93772. onError(request.status + " " + request.statusText, exception);
  93773. }
  93774. });
  93775. };
  93776. return BinaryFileAssetTask;
  93777. }(AbstractAssetTask));
  93778. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93779. /**
  93780. * Define a task used by {BABYLON.AssetsManager} to load images
  93781. */
  93782. var ImageAssetTask = /** @class */ (function (_super) {
  93783. __extends(ImageAssetTask, _super);
  93784. /**
  93785. * Creates a new ImageAssetTask
  93786. * @param name defines the name of the task
  93787. * @param url defines the location of the image to load
  93788. */
  93789. function ImageAssetTask(
  93790. /**
  93791. * Defines the name of the task
  93792. */
  93793. name,
  93794. /**
  93795. * Defines the location of the image to load
  93796. */
  93797. url) {
  93798. var _this = _super.call(this, name) || this;
  93799. _this.name = name;
  93800. _this.url = url;
  93801. return _this;
  93802. }
  93803. /**
  93804. * Execute the current task
  93805. * @param scene defines the scene where you want your assets to be loaded
  93806. * @param onSuccess is a callback called when the task is successfully executed
  93807. * @param onError is a callback called if an error occurs
  93808. */
  93809. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93810. var _this = this;
  93811. var img = new Image();
  93812. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93813. img.onload = function () {
  93814. _this.image = img;
  93815. onSuccess();
  93816. };
  93817. img.onerror = function (err) {
  93818. onError("Error loading image", err);
  93819. };
  93820. img.src = this.url;
  93821. };
  93822. return ImageAssetTask;
  93823. }(AbstractAssetTask));
  93824. BABYLON.ImageAssetTask = ImageAssetTask;
  93825. /**
  93826. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93827. */
  93828. var TextureAssetTask = /** @class */ (function (_super) {
  93829. __extends(TextureAssetTask, _super);
  93830. /**
  93831. * Creates a new TextureAssetTask object
  93832. * @param name defines the name of the task
  93833. * @param url defines the location of the file to load
  93834. * @param noMipmap defines if mipmap should not be generated (default is false)
  93835. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93836. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93837. */
  93838. function TextureAssetTask(
  93839. /**
  93840. * Defines the name of the task
  93841. */
  93842. name,
  93843. /**
  93844. * Defines the location of the file to load
  93845. */
  93846. url,
  93847. /**
  93848. * Defines if mipmap should not be generated (default is false)
  93849. */
  93850. noMipmap,
  93851. /**
  93852. * Defines if texture must be inverted on Y axis (default is false)
  93853. */
  93854. invertY,
  93855. /**
  93856. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93857. */
  93858. samplingMode) {
  93859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93860. var _this = _super.call(this, name) || this;
  93861. _this.name = name;
  93862. _this.url = url;
  93863. _this.noMipmap = noMipmap;
  93864. _this.invertY = invertY;
  93865. _this.samplingMode = samplingMode;
  93866. return _this;
  93867. }
  93868. /**
  93869. * Execute the current task
  93870. * @param scene defines the scene where you want your assets to be loaded
  93871. * @param onSuccess is a callback called when the task is successfully executed
  93872. * @param onError is a callback called if an error occurs
  93873. */
  93874. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93875. var onload = function () {
  93876. onSuccess();
  93877. };
  93878. var onerror = function (message, exception) {
  93879. onError(message, exception);
  93880. };
  93881. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93882. };
  93883. return TextureAssetTask;
  93884. }(AbstractAssetTask));
  93885. BABYLON.TextureAssetTask = TextureAssetTask;
  93886. /**
  93887. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93888. */
  93889. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93890. __extends(CubeTextureAssetTask, _super);
  93891. /**
  93892. * Creates a new CubeTextureAssetTask
  93893. * @param name defines the name of the task
  93894. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93895. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93896. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93897. * @param files defines the explicit list of files (undefined by default)
  93898. */
  93899. function CubeTextureAssetTask(
  93900. /**
  93901. * Defines the name of the task
  93902. */
  93903. name,
  93904. /**
  93905. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93906. */
  93907. url,
  93908. /**
  93909. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93910. */
  93911. extensions,
  93912. /**
  93913. * Defines if mipmaps should not be generated (default is false)
  93914. */
  93915. noMipmap,
  93916. /**
  93917. * Defines the explicit list of files (undefined by default)
  93918. */
  93919. files) {
  93920. var _this = _super.call(this, name) || this;
  93921. _this.name = name;
  93922. _this.url = url;
  93923. _this.extensions = extensions;
  93924. _this.noMipmap = noMipmap;
  93925. _this.files = files;
  93926. return _this;
  93927. }
  93928. /**
  93929. * Execute the current task
  93930. * @param scene defines the scene where you want your assets to be loaded
  93931. * @param onSuccess is a callback called when the task is successfully executed
  93932. * @param onError is a callback called if an error occurs
  93933. */
  93934. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93935. var onload = function () {
  93936. onSuccess();
  93937. };
  93938. var onerror = function (message, exception) {
  93939. onError(message, exception);
  93940. };
  93941. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93942. };
  93943. return CubeTextureAssetTask;
  93944. }(AbstractAssetTask));
  93945. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93946. /**
  93947. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93948. */
  93949. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93950. __extends(HDRCubeTextureAssetTask, _super);
  93951. /**
  93952. * Creates a new HDRCubeTextureAssetTask object
  93953. * @param name defines the name of the task
  93954. * @param url defines the location of the file to load
  93955. * @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.
  93956. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93957. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93958. * @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)
  93959. * @param reserved Internal use only
  93960. */
  93961. function HDRCubeTextureAssetTask(
  93962. /**
  93963. * Defines the name of the task
  93964. */
  93965. name,
  93966. /**
  93967. * Defines the location of the file to load
  93968. */
  93969. url,
  93970. /**
  93971. * Defines the desired size (the more it increases the longer the generation will be)
  93972. */
  93973. size,
  93974. /**
  93975. * Defines if mipmaps should not be generated (default is false)
  93976. */
  93977. noMipmap,
  93978. /**
  93979. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93980. */
  93981. generateHarmonics,
  93982. /**
  93983. * 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)
  93984. */
  93985. gammaSpace,
  93986. /**
  93987. * Internal Use Only
  93988. */
  93989. reserved) {
  93990. if (noMipmap === void 0) { noMipmap = false; }
  93991. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93992. if (gammaSpace === void 0) { gammaSpace = false; }
  93993. if (reserved === void 0) { reserved = false; }
  93994. var _this = _super.call(this, name) || this;
  93995. _this.name = name;
  93996. _this.url = url;
  93997. _this.size = size;
  93998. _this.noMipmap = noMipmap;
  93999. _this.generateHarmonics = generateHarmonics;
  94000. _this.gammaSpace = gammaSpace;
  94001. _this.reserved = reserved;
  94002. return _this;
  94003. }
  94004. /**
  94005. * Execute the current task
  94006. * @param scene defines the scene where you want your assets to be loaded
  94007. * @param onSuccess is a callback called when the task is successfully executed
  94008. * @param onError is a callback called if an error occurs
  94009. */
  94010. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  94011. var onload = function () {
  94012. onSuccess();
  94013. };
  94014. var onerror = function (message, exception) {
  94015. onError(message, exception);
  94016. };
  94017. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  94018. };
  94019. return HDRCubeTextureAssetTask;
  94020. }(AbstractAssetTask));
  94021. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  94022. /**
  94023. * This class can be used to easily import assets into a scene
  94024. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  94025. */
  94026. var AssetsManager = /** @class */ (function () {
  94027. /**
  94028. * Creates a new AssetsManager
  94029. * @param scene defines the scene to work on
  94030. */
  94031. function AssetsManager(scene) {
  94032. this._isLoading = false;
  94033. this._tasks = new Array();
  94034. this._waitingTasksCount = 0;
  94035. this._totalTasksCount = 0;
  94036. /**
  94037. * Observable called when all tasks are processed
  94038. */
  94039. this.onTaskSuccessObservable = new BABYLON.Observable();
  94040. /**
  94041. * Observable called when a task had an error
  94042. */
  94043. this.onTaskErrorObservable = new BABYLON.Observable();
  94044. /**
  94045. * Observable called when a task is successful
  94046. */
  94047. this.onTasksDoneObservable = new BABYLON.Observable();
  94048. /**
  94049. * Observable called when a task is done (whatever the result is)
  94050. */
  94051. this.onProgressObservable = new BABYLON.Observable();
  94052. /**
  94053. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  94054. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  94055. */
  94056. this.useDefaultLoadingScreen = true;
  94057. this._scene = scene;
  94058. }
  94059. /**
  94060. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  94061. * @param taskName defines the name of the new task
  94062. * @param meshesNames defines the name of meshes to load
  94063. * @param rootUrl defines the root url to use to locate files
  94064. * @param sceneFilename defines the filename of the scene file
  94065. * @returns a new {BABYLON.MeshAssetTask} object
  94066. */
  94067. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  94068. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  94069. this._tasks.push(task);
  94070. return task;
  94071. };
  94072. /**
  94073. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  94074. * @param taskName defines the name of the new task
  94075. * @param url defines the url of the file to load
  94076. * @returns a new {BABYLON.TextFileAssetTask} object
  94077. */
  94078. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  94079. var task = new TextFileAssetTask(taskName, url);
  94080. this._tasks.push(task);
  94081. return task;
  94082. };
  94083. /**
  94084. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  94085. * @param taskName defines the name of the new task
  94086. * @param url defines the url of the file to load
  94087. * @returns a new {BABYLON.BinaryFileAssetTask} object
  94088. */
  94089. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  94090. var task = new BinaryFileAssetTask(taskName, url);
  94091. this._tasks.push(task);
  94092. return task;
  94093. };
  94094. /**
  94095. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  94096. * @param taskName defines the name of the new task
  94097. * @param url defines the url of the file to load
  94098. * @returns a new {BABYLON.ImageAssetTask} object
  94099. */
  94100. AssetsManager.prototype.addImageTask = function (taskName, url) {
  94101. var task = new ImageAssetTask(taskName, url);
  94102. this._tasks.push(task);
  94103. return task;
  94104. };
  94105. /**
  94106. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  94107. * @param taskName defines the name of the new task
  94108. * @param url defines the url of the file to load
  94109. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94110. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  94111. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  94112. * @returns a new {BABYLON.TextureAssetTask} object
  94113. */
  94114. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  94115. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94116. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  94117. this._tasks.push(task);
  94118. return task;
  94119. };
  94120. /**
  94121. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  94122. * @param taskName defines the name of the new task
  94123. * @param url defines the url of the file to load
  94124. * @param extensions defines the extension to use to load the cube map (can be null)
  94125. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94126. * @param files defines the list of files to load (can be null)
  94127. * @returns a new {BABYLON.CubeTextureAssetTask} object
  94128. */
  94129. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  94130. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  94131. this._tasks.push(task);
  94132. return task;
  94133. };
  94134. /**
  94135. *
  94136. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  94137. * @param taskName defines the name of the new task
  94138. * @param url defines the url of the file to load
  94139. * @param size defines the size you want for the cubemap (can be null)
  94140. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94141. * @param generateHarmonics defines if you want to automatically generate (true by default)
  94142. * @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)
  94143. * @param reserved Internal use only
  94144. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  94145. */
  94146. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  94147. if (noMipmap === void 0) { noMipmap = false; }
  94148. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94149. if (gammaSpace === void 0) { gammaSpace = false; }
  94150. if (reserved === void 0) { reserved = false; }
  94151. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  94152. this._tasks.push(task);
  94153. return task;
  94154. };
  94155. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  94156. this._waitingTasksCount--;
  94157. try {
  94158. if (this.onProgress) {
  94159. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  94160. }
  94161. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  94162. }
  94163. catch (e) {
  94164. BABYLON.Tools.Error("Error running progress callbacks.");
  94165. console.log(e);
  94166. }
  94167. if (this._waitingTasksCount === 0) {
  94168. try {
  94169. if (this.onFinish) {
  94170. this.onFinish(this._tasks);
  94171. }
  94172. // Let's remove successfull tasks
  94173. var currentTasks = this._tasks.slice();
  94174. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  94175. var task = currentTasks_1[_i];
  94176. if (task.taskState === AssetTaskState.DONE) {
  94177. var index = this._tasks.indexOf(task);
  94178. if (index > -1) {
  94179. this._tasks.splice(index, 1);
  94180. }
  94181. }
  94182. }
  94183. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94184. }
  94185. catch (e) {
  94186. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  94187. console.log(e);
  94188. }
  94189. this._isLoading = false;
  94190. this._scene.getEngine().hideLoadingUI();
  94191. }
  94192. };
  94193. AssetsManager.prototype._runTask = function (task) {
  94194. var _this = this;
  94195. var done = function () {
  94196. try {
  94197. if (_this.onTaskSuccess) {
  94198. _this.onTaskSuccess(task);
  94199. }
  94200. _this.onTaskSuccessObservable.notifyObservers(task);
  94201. _this._decreaseWaitingTasksCount(task);
  94202. }
  94203. catch (e) {
  94204. error("Error executing task success callbacks", e);
  94205. }
  94206. };
  94207. var error = function (message, exception) {
  94208. task._setErrorObject(message, exception);
  94209. if (_this.onTaskError) {
  94210. _this.onTaskError(task);
  94211. }
  94212. _this.onTaskErrorObservable.notifyObservers(task);
  94213. _this._decreaseWaitingTasksCount(task);
  94214. };
  94215. task.run(this._scene, done, error);
  94216. };
  94217. /**
  94218. * Reset the {BABYLON.AssetsManager} and remove all tasks
  94219. * @return the current instance of the {BABYLON.AssetsManager}
  94220. */
  94221. AssetsManager.prototype.reset = function () {
  94222. this._isLoading = false;
  94223. this._tasks = new Array();
  94224. return this;
  94225. };
  94226. /**
  94227. * Start the loading process
  94228. * @return the current instance of the {BABYLON.AssetsManager}
  94229. */
  94230. AssetsManager.prototype.load = function () {
  94231. if (this._isLoading) {
  94232. return this;
  94233. }
  94234. this._isLoading = true;
  94235. this._waitingTasksCount = this._tasks.length;
  94236. this._totalTasksCount = this._tasks.length;
  94237. if (this._waitingTasksCount === 0) {
  94238. this._isLoading = false;
  94239. if (this.onFinish) {
  94240. this.onFinish(this._tasks);
  94241. }
  94242. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94243. return this;
  94244. }
  94245. if (this.useDefaultLoadingScreen) {
  94246. this._scene.getEngine().displayLoadingUI();
  94247. }
  94248. for (var index = 0; index < this._tasks.length; index++) {
  94249. var task = this._tasks[index];
  94250. this._runTask(task);
  94251. }
  94252. return this;
  94253. };
  94254. return AssetsManager;
  94255. }());
  94256. BABYLON.AssetsManager = AssetsManager;
  94257. })(BABYLON || (BABYLON = {}));
  94258. //# sourceMappingURL=babylon.assetsManager.js.map
  94259. var BABYLON;
  94260. (function (BABYLON) {
  94261. var serializedGeometries = [];
  94262. var serializeGeometry = function (geometry, serializationGeometries) {
  94263. if (serializedGeometries[geometry.id]) {
  94264. return;
  94265. }
  94266. if (geometry.doNotSerialize) {
  94267. return;
  94268. }
  94269. if (geometry instanceof BABYLON.BoxGeometry) {
  94270. serializationGeometries.boxes.push(geometry.serialize());
  94271. }
  94272. else if (geometry instanceof BABYLON.SphereGeometry) {
  94273. serializationGeometries.spheres.push(geometry.serialize());
  94274. }
  94275. else if (geometry instanceof BABYLON.CylinderGeometry) {
  94276. serializationGeometries.cylinders.push(geometry.serialize());
  94277. }
  94278. else if (geometry instanceof BABYLON.TorusGeometry) {
  94279. serializationGeometries.toruses.push(geometry.serialize());
  94280. }
  94281. else if (geometry instanceof BABYLON.GroundGeometry) {
  94282. serializationGeometries.grounds.push(geometry.serialize());
  94283. }
  94284. else if (geometry instanceof BABYLON.Plane) {
  94285. serializationGeometries.planes.push(geometry.serialize());
  94286. }
  94287. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  94288. serializationGeometries.torusKnots.push(geometry.serialize());
  94289. }
  94290. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  94291. throw new Error("Unknown primitive type");
  94292. }
  94293. else {
  94294. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  94295. }
  94296. serializedGeometries[geometry.id] = true;
  94297. };
  94298. var serializeMesh = function (mesh, serializationScene) {
  94299. var serializationObject = {};
  94300. // Geometry
  94301. var geometry = mesh._geometry;
  94302. if (geometry) {
  94303. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  94304. // 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
  94305. serializeGeometry(geometry, serializationScene.geometries);
  94306. }
  94307. }
  94308. // Custom
  94309. if (mesh.serialize) {
  94310. mesh.serialize(serializationObject);
  94311. }
  94312. return serializationObject;
  94313. };
  94314. var finalizeSingleMesh = function (mesh, serializationObject) {
  94315. //only works if the mesh is already loaded
  94316. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94317. //serialize material
  94318. if (mesh.material) {
  94319. if (mesh.material instanceof BABYLON.StandardMaterial) {
  94320. serializationObject.materials = serializationObject.materials || [];
  94321. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94322. serializationObject.materials.push(mesh.material.serialize());
  94323. }
  94324. }
  94325. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  94326. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  94327. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94328. serializationObject.multiMaterials.push(mesh.material.serialize());
  94329. }
  94330. }
  94331. }
  94332. //serialize geometry
  94333. var geometry = mesh._geometry;
  94334. if (geometry) {
  94335. if (!serializationObject.geometries) {
  94336. serializationObject.geometries = {};
  94337. serializationObject.geometries.boxes = [];
  94338. serializationObject.geometries.spheres = [];
  94339. serializationObject.geometries.cylinders = [];
  94340. serializationObject.geometries.toruses = [];
  94341. serializationObject.geometries.grounds = [];
  94342. serializationObject.geometries.planes = [];
  94343. serializationObject.geometries.torusKnots = [];
  94344. serializationObject.geometries.vertexData = [];
  94345. }
  94346. serializeGeometry(geometry, serializationObject.geometries);
  94347. }
  94348. // Skeletons
  94349. if (mesh.skeleton) {
  94350. serializationObject.skeletons = serializationObject.skeletons || [];
  94351. serializationObject.skeletons.push(mesh.skeleton.serialize());
  94352. }
  94353. //serialize the actual mesh
  94354. serializationObject.meshes = serializationObject.meshes || [];
  94355. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94356. }
  94357. };
  94358. var SceneSerializer = /** @class */ (function () {
  94359. function SceneSerializer() {
  94360. }
  94361. SceneSerializer.ClearCache = function () {
  94362. serializedGeometries = [];
  94363. };
  94364. SceneSerializer.Serialize = function (scene) {
  94365. var serializationObject = {};
  94366. SceneSerializer.ClearCache();
  94367. // Scene
  94368. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94369. serializationObject.autoClear = scene.autoClear;
  94370. serializationObject.clearColor = scene.clearColor.asArray();
  94371. serializationObject.ambientColor = scene.ambientColor.asArray();
  94372. serializationObject.gravity = scene.gravity.asArray();
  94373. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94374. serializationObject.workerCollisions = scene.workerCollisions;
  94375. // Fog
  94376. if (scene.fogMode && scene.fogMode !== 0) {
  94377. serializationObject.fogMode = scene.fogMode;
  94378. serializationObject.fogColor = scene.fogColor.asArray();
  94379. serializationObject.fogStart = scene.fogStart;
  94380. serializationObject.fogEnd = scene.fogEnd;
  94381. serializationObject.fogDensity = scene.fogDensity;
  94382. }
  94383. //Physics
  94384. if (scene.isPhysicsEnabled()) {
  94385. var physicEngine = scene.getPhysicsEngine();
  94386. if (physicEngine) {
  94387. serializationObject.physicsEnabled = true;
  94388. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94389. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94390. }
  94391. }
  94392. // Metadata
  94393. if (scene.metadata) {
  94394. serializationObject.metadata = scene.metadata;
  94395. }
  94396. // Morph targets
  94397. serializationObject.morphTargetManagers = [];
  94398. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94399. var abstractMesh = _a[_i];
  94400. var manager = abstractMesh.morphTargetManager;
  94401. if (manager) {
  94402. serializationObject.morphTargetManagers.push(manager.serialize());
  94403. }
  94404. }
  94405. // Lights
  94406. serializationObject.lights = [];
  94407. var index;
  94408. var light;
  94409. for (index = 0; index < scene.lights.length; index++) {
  94410. light = scene.lights[index];
  94411. if (!light.doNotSerialize) {
  94412. serializationObject.lights.push(light.serialize());
  94413. }
  94414. }
  94415. // Cameras
  94416. serializationObject.cameras = [];
  94417. for (index = 0; index < scene.cameras.length; index++) {
  94418. var camera = scene.cameras[index];
  94419. if (!camera.doNotSerialize) {
  94420. serializationObject.cameras.push(camera.serialize());
  94421. }
  94422. }
  94423. if (scene.activeCamera) {
  94424. serializationObject.activeCameraID = scene.activeCamera.id;
  94425. }
  94426. // Animations
  94427. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94428. // Materials
  94429. serializationObject.materials = [];
  94430. serializationObject.multiMaterials = [];
  94431. var material;
  94432. for (index = 0; index < scene.materials.length; index++) {
  94433. material = scene.materials[index];
  94434. if (!material.doNotSerialize) {
  94435. serializationObject.materials.push(material.serialize());
  94436. }
  94437. }
  94438. // MultiMaterials
  94439. serializationObject.multiMaterials = [];
  94440. for (index = 0; index < scene.multiMaterials.length; index++) {
  94441. var multiMaterial = scene.multiMaterials[index];
  94442. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94443. }
  94444. // Environment texture
  94445. if (scene.environmentTexture) {
  94446. serializationObject.environmentTexture = scene.environmentTexture.name;
  94447. }
  94448. // Skeletons
  94449. serializationObject.skeletons = [];
  94450. for (index = 0; index < scene.skeletons.length; index++) {
  94451. var skeleton = scene.skeletons[index];
  94452. if (!skeleton.doNotSerialize) {
  94453. serializationObject.skeletons.push(skeleton.serialize());
  94454. }
  94455. }
  94456. // Transform nodes
  94457. serializationObject.transformNodes = [];
  94458. for (index = 0; index < scene.transformNodes.length; index++) {
  94459. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94460. }
  94461. // Geometries
  94462. serializationObject.geometries = {};
  94463. serializationObject.geometries.boxes = [];
  94464. serializationObject.geometries.spheres = [];
  94465. serializationObject.geometries.cylinders = [];
  94466. serializationObject.geometries.toruses = [];
  94467. serializationObject.geometries.grounds = [];
  94468. serializationObject.geometries.planes = [];
  94469. serializationObject.geometries.torusKnots = [];
  94470. serializationObject.geometries.vertexData = [];
  94471. serializedGeometries = [];
  94472. var geometries = scene.getGeometries();
  94473. for (index = 0; index < geometries.length; index++) {
  94474. var geometry = geometries[index];
  94475. if (geometry.isReady()) {
  94476. serializeGeometry(geometry, serializationObject.geometries);
  94477. }
  94478. }
  94479. // Meshes
  94480. serializationObject.meshes = [];
  94481. for (index = 0; index < scene.meshes.length; index++) {
  94482. var abstractMesh = scene.meshes[index];
  94483. if (abstractMesh instanceof BABYLON.Mesh) {
  94484. var mesh = abstractMesh;
  94485. if (!mesh.doNotSerialize) {
  94486. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94487. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94488. }
  94489. }
  94490. }
  94491. }
  94492. // Particles Systems
  94493. serializationObject.particleSystems = [];
  94494. for (index = 0; index < scene.particleSystems.length; index++) {
  94495. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94496. }
  94497. // Lens flares
  94498. serializationObject.lensFlareSystems = [];
  94499. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94500. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94501. }
  94502. // Shadows
  94503. serializationObject.shadowGenerators = [];
  94504. for (index = 0; index < scene.lights.length; index++) {
  94505. light = scene.lights[index];
  94506. var shadowGenerator = light.getShadowGenerator();
  94507. if (shadowGenerator) {
  94508. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94509. }
  94510. }
  94511. // Action Manager
  94512. if (scene.actionManager) {
  94513. serializationObject.actions = scene.actionManager.serialize("scene");
  94514. }
  94515. // Audio
  94516. serializationObject.sounds = [];
  94517. for (index = 0; index < scene.soundTracks.length; index++) {
  94518. var soundtrack = scene.soundTracks[index];
  94519. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94520. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94521. }
  94522. }
  94523. // Effect layers
  94524. serializationObject.effectLayers = [];
  94525. for (index = 0; index < scene.effectLayers.length; index++) {
  94526. var layer = scene.effectLayers[index];
  94527. if (layer.serialize) {
  94528. serializationObject.effectLayers.push(layer.serialize());
  94529. }
  94530. }
  94531. return serializationObject;
  94532. };
  94533. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94534. if (withParents === void 0) { withParents = false; }
  94535. if (withChildren === void 0) { withChildren = false; }
  94536. var serializationObject = {};
  94537. SceneSerializer.ClearCache();
  94538. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94539. if (withParents || withChildren) {
  94540. //deliberate for loop! not for each, appended should be processed as well.
  94541. for (var i = 0; i < toSerialize.length; ++i) {
  94542. if (withChildren) {
  94543. toSerialize[i].getDescendants().forEach(function (node) {
  94544. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94545. toSerialize.push(node);
  94546. }
  94547. });
  94548. }
  94549. //make sure the array doesn't contain the object already
  94550. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94551. toSerialize.push(toSerialize[i].parent);
  94552. }
  94553. }
  94554. }
  94555. toSerialize.forEach(function (mesh) {
  94556. finalizeSingleMesh(mesh, serializationObject);
  94557. });
  94558. return serializationObject;
  94559. };
  94560. return SceneSerializer;
  94561. }());
  94562. BABYLON.SceneSerializer = SceneSerializer;
  94563. })(BABYLON || (BABYLON = {}));
  94564. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94565. var BABYLON;
  94566. (function (BABYLON) {
  94567. var ReflectionProbe = /** @class */ (function () {
  94568. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94569. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94570. var _this = this;
  94571. this.name = name;
  94572. this._viewMatrix = BABYLON.Matrix.Identity();
  94573. this._target = BABYLON.Vector3.Zero();
  94574. this._add = BABYLON.Vector3.Zero();
  94575. this._invertYAxis = false;
  94576. this.position = BABYLON.Vector3.Zero();
  94577. this._scene = scene;
  94578. this._scene.reflectionProbes.push(this);
  94579. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94580. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94581. switch (faceIndex) {
  94582. case 0:
  94583. _this._add.copyFromFloats(1, 0, 0);
  94584. break;
  94585. case 1:
  94586. _this._add.copyFromFloats(-1, 0, 0);
  94587. break;
  94588. case 2:
  94589. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94590. break;
  94591. case 3:
  94592. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94593. break;
  94594. case 4:
  94595. _this._add.copyFromFloats(0, 0, 1);
  94596. break;
  94597. case 5:
  94598. _this._add.copyFromFloats(0, 0, -1);
  94599. break;
  94600. }
  94601. if (_this._attachedMesh) {
  94602. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94603. }
  94604. _this.position.addToRef(_this._add, _this._target);
  94605. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94606. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94607. scene._forcedViewPosition = _this.position;
  94608. });
  94609. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94610. scene._forcedViewPosition = null;
  94611. scene.updateTransformMatrix(true);
  94612. });
  94613. if (scene.activeCamera) {
  94614. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94615. }
  94616. }
  94617. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94618. get: function () {
  94619. return this._renderTargetTexture.samples;
  94620. },
  94621. set: function (value) {
  94622. this._renderTargetTexture.samples = value;
  94623. },
  94624. enumerable: true,
  94625. configurable: true
  94626. });
  94627. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94628. get: function () {
  94629. return this._renderTargetTexture.refreshRate;
  94630. },
  94631. set: function (value) {
  94632. this._renderTargetTexture.refreshRate = value;
  94633. },
  94634. enumerable: true,
  94635. configurable: true
  94636. });
  94637. ReflectionProbe.prototype.getScene = function () {
  94638. return this._scene;
  94639. };
  94640. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94641. get: function () {
  94642. return this._renderTargetTexture;
  94643. },
  94644. enumerable: true,
  94645. configurable: true
  94646. });
  94647. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94648. get: function () {
  94649. return this._renderTargetTexture.renderList;
  94650. },
  94651. enumerable: true,
  94652. configurable: true
  94653. });
  94654. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94655. this._attachedMesh = mesh;
  94656. };
  94657. /**
  94658. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94659. *
  94660. * @param renderingGroupId The rendering group id corresponding to its index
  94661. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94662. */
  94663. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94664. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94665. };
  94666. ReflectionProbe.prototype.dispose = function () {
  94667. var index = this._scene.reflectionProbes.indexOf(this);
  94668. if (index !== -1) {
  94669. // Remove from the scene if found
  94670. this._scene.reflectionProbes.splice(index, 1);
  94671. }
  94672. if (this._renderTargetTexture) {
  94673. this._renderTargetTexture.dispose();
  94674. this._renderTargetTexture = null;
  94675. }
  94676. };
  94677. return ReflectionProbe;
  94678. }());
  94679. BABYLON.ReflectionProbe = ReflectionProbe;
  94680. })(BABYLON || (BABYLON = {}));
  94681. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94682. var BABYLON;
  94683. (function (BABYLON) {
  94684. var Layer = /** @class */ (function () {
  94685. function Layer(name, imgUrl, scene, isBackground, color) {
  94686. this.name = name;
  94687. this.scale = new BABYLON.Vector2(1, 1);
  94688. this.offset = new BABYLON.Vector2(0, 0);
  94689. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94690. this.layerMask = 0x0FFFFFFF;
  94691. this._vertexBuffers = {};
  94692. // Events
  94693. /**
  94694. * An event triggered when the layer is disposed.
  94695. */
  94696. this.onDisposeObservable = new BABYLON.Observable();
  94697. /**
  94698. * An event triggered before rendering the scene
  94699. */
  94700. this.onBeforeRenderObservable = new BABYLON.Observable();
  94701. /**
  94702. * An event triggered after rendering the scene
  94703. */
  94704. this.onAfterRenderObservable = new BABYLON.Observable();
  94705. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94706. this.isBackground = isBackground === undefined ? true : isBackground;
  94707. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94708. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94709. this._scene.layers.push(this);
  94710. var engine = this._scene.getEngine();
  94711. // VBO
  94712. var vertices = [];
  94713. vertices.push(1, 1);
  94714. vertices.push(-1, 1);
  94715. vertices.push(-1, -1);
  94716. vertices.push(1, -1);
  94717. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94718. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94719. this._createIndexBuffer();
  94720. // Effects
  94721. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94722. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94723. }
  94724. Object.defineProperty(Layer.prototype, "onDispose", {
  94725. set: function (callback) {
  94726. if (this._onDisposeObserver) {
  94727. this.onDisposeObservable.remove(this._onDisposeObserver);
  94728. }
  94729. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94730. },
  94731. enumerable: true,
  94732. configurable: true
  94733. });
  94734. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94735. set: function (callback) {
  94736. if (this._onBeforeRenderObserver) {
  94737. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94738. }
  94739. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94740. },
  94741. enumerable: true,
  94742. configurable: true
  94743. });
  94744. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94745. set: function (callback) {
  94746. if (this._onAfterRenderObserver) {
  94747. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94748. }
  94749. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94750. },
  94751. enumerable: true,
  94752. configurable: true
  94753. });
  94754. Layer.prototype._createIndexBuffer = function () {
  94755. var engine = this._scene.getEngine();
  94756. // Indices
  94757. var indices = [];
  94758. indices.push(0);
  94759. indices.push(1);
  94760. indices.push(2);
  94761. indices.push(0);
  94762. indices.push(2);
  94763. indices.push(3);
  94764. this._indexBuffer = engine.createIndexBuffer(indices);
  94765. };
  94766. Layer.prototype._rebuild = function () {
  94767. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94768. if (vb) {
  94769. vb._rebuild();
  94770. }
  94771. this._createIndexBuffer();
  94772. };
  94773. Layer.prototype.render = function () {
  94774. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94775. // Check
  94776. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94777. return;
  94778. var engine = this._scene.getEngine();
  94779. this.onBeforeRenderObservable.notifyObservers(this);
  94780. // Render
  94781. engine.enableEffect(currentEffect);
  94782. engine.setState(false);
  94783. // Texture
  94784. currentEffect.setTexture("textureSampler", this.texture);
  94785. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94786. // Color
  94787. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94788. // Scale / offset
  94789. currentEffect.setVector2("offset", this.offset);
  94790. currentEffect.setVector2("scale", this.scale);
  94791. // VBOs
  94792. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94793. // Draw order
  94794. if (!this.alphaTest) {
  94795. engine.setAlphaMode(this.alphaBlendingMode);
  94796. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94797. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94798. }
  94799. else {
  94800. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94801. }
  94802. this.onAfterRenderObservable.notifyObservers(this);
  94803. };
  94804. Layer.prototype.dispose = function () {
  94805. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94806. if (vertexBuffer) {
  94807. vertexBuffer.dispose();
  94808. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94809. }
  94810. if (this._indexBuffer) {
  94811. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94812. this._indexBuffer = null;
  94813. }
  94814. if (this.texture) {
  94815. this.texture.dispose();
  94816. this.texture = null;
  94817. }
  94818. // Remove from scene
  94819. var index = this._scene.layers.indexOf(this);
  94820. this._scene.layers.splice(index, 1);
  94821. // Callback
  94822. this.onDisposeObservable.notifyObservers(this);
  94823. this.onDisposeObservable.clear();
  94824. this.onAfterRenderObservable.clear();
  94825. this.onBeforeRenderObservable.clear();
  94826. };
  94827. return Layer;
  94828. }());
  94829. BABYLON.Layer = Layer;
  94830. })(BABYLON || (BABYLON = {}));
  94831. //# sourceMappingURL=babylon.layer.js.map
  94832. var BABYLON;
  94833. (function (BABYLON) {
  94834. var TextureTools = /** @class */ (function () {
  94835. function TextureTools() {
  94836. }
  94837. /**
  94838. * Uses the GPU to create a copy texture rescaled at a given size
  94839. * @param texture Texture to copy from
  94840. * @param width Desired width
  94841. * @param height Desired height
  94842. * @return Generated texture
  94843. */
  94844. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94845. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94846. var scene = texture.getScene();
  94847. var engine = scene.getEngine();
  94848. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94849. rtt.wrapU = texture.wrapU;
  94850. rtt.wrapV = texture.wrapV;
  94851. rtt.uOffset = texture.uOffset;
  94852. rtt.vOffset = texture.vOffset;
  94853. rtt.uScale = texture.uScale;
  94854. rtt.vScale = texture.vScale;
  94855. rtt.uAng = texture.uAng;
  94856. rtt.vAng = texture.vAng;
  94857. rtt.wAng = texture.wAng;
  94858. rtt.coordinatesIndex = texture.coordinatesIndex;
  94859. rtt.level = texture.level;
  94860. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94861. rtt._texture.isReady = false;
  94862. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94863. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94864. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94865. passPostProcess.getEffect().executeWhenCompiled(function () {
  94866. passPostProcess.onApply = function (effect) {
  94867. effect.setTexture("textureSampler", texture);
  94868. };
  94869. var internalTexture = rtt.getInternalTexture();
  94870. if (internalTexture) {
  94871. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94872. engine.unBindFramebuffer(internalTexture);
  94873. rtt.disposeFramebufferObjects();
  94874. passPostProcess.dispose();
  94875. internalTexture.isReady = true;
  94876. }
  94877. });
  94878. return rtt;
  94879. };
  94880. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94881. if (!scene._environmentBRDFTexture) {
  94882. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94883. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94884. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94885. scene._environmentBRDFTexture = texture;
  94886. }
  94887. return scene._environmentBRDFTexture;
  94888. };
  94889. 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=";
  94890. return TextureTools;
  94891. }());
  94892. BABYLON.TextureTools = TextureTools;
  94893. })(BABYLON || (BABYLON = {}));
  94894. //# sourceMappingURL=babylon.textureTools.js.map
  94895. var BABYLON;
  94896. (function (BABYLON) {
  94897. var FramingBehavior = /** @class */ (function () {
  94898. function FramingBehavior() {
  94899. this._mode = FramingBehavior.FitFrustumSidesMode;
  94900. this._radiusScale = 1.0;
  94901. this._positionScale = 0.5;
  94902. this._defaultElevation = 0.3;
  94903. this._elevationReturnTime = 1500;
  94904. this._elevationReturnWaitTime = 1000;
  94905. this._zoomStopsAnimation = false;
  94906. this._framingTime = 1500;
  94907. this._isPointerDown = false;
  94908. this._lastInteractionTime = -Infinity;
  94909. // Framing control
  94910. this._animatables = new Array();
  94911. this._betaIsAnimating = false;
  94912. }
  94913. Object.defineProperty(FramingBehavior.prototype, "name", {
  94914. get: function () {
  94915. return "Framing";
  94916. },
  94917. enumerable: true,
  94918. configurable: true
  94919. });
  94920. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94921. /**
  94922. * Gets current mode used by the behavior.
  94923. */
  94924. get: function () {
  94925. return this._mode;
  94926. },
  94927. /**
  94928. * Sets the current mode used by the behavior
  94929. */
  94930. set: function (mode) {
  94931. this._mode = mode;
  94932. },
  94933. enumerable: true,
  94934. configurable: true
  94935. });
  94936. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94937. /**
  94938. * Gets the scale applied to the radius
  94939. */
  94940. get: function () {
  94941. return this._radiusScale;
  94942. },
  94943. /**
  94944. * Sets the scale applied to the radius (1 by default)
  94945. */
  94946. set: function (radius) {
  94947. this._radiusScale = radius;
  94948. },
  94949. enumerable: true,
  94950. configurable: true
  94951. });
  94952. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94953. /**
  94954. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94955. */
  94956. get: function () {
  94957. return this._positionScale;
  94958. },
  94959. /**
  94960. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94961. */
  94962. set: function (scale) {
  94963. this._positionScale = scale;
  94964. },
  94965. enumerable: true,
  94966. configurable: true
  94967. });
  94968. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94969. /**
  94970. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94971. * behaviour is triggered, in radians.
  94972. */
  94973. get: function () {
  94974. return this._defaultElevation;
  94975. },
  94976. /**
  94977. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94978. * behaviour is triggered, in radians.
  94979. */
  94980. set: function (elevation) {
  94981. this._defaultElevation = elevation;
  94982. },
  94983. enumerable: true,
  94984. configurable: true
  94985. });
  94986. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94987. /**
  94988. * Gets the time (in milliseconds) taken to return to the default beta position.
  94989. * Negative value indicates camera should not return to default.
  94990. */
  94991. get: function () {
  94992. return this._elevationReturnTime;
  94993. },
  94994. /**
  94995. * Sets the time (in milliseconds) taken to return to the default beta position.
  94996. * Negative value indicates camera should not return to default.
  94997. */
  94998. set: function (speed) {
  94999. this._elevationReturnTime = speed;
  95000. },
  95001. enumerable: true,
  95002. configurable: true
  95003. });
  95004. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  95005. /**
  95006. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95007. */
  95008. get: function () {
  95009. return this._elevationReturnWaitTime;
  95010. },
  95011. /**
  95012. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95013. */
  95014. set: function (time) {
  95015. this._elevationReturnWaitTime = time;
  95016. },
  95017. enumerable: true,
  95018. configurable: true
  95019. });
  95020. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  95021. /**
  95022. * Gets the flag that indicates if user zooming should stop animation.
  95023. */
  95024. get: function () {
  95025. return this._zoomStopsAnimation;
  95026. },
  95027. /**
  95028. * Sets the flag that indicates if user zooming should stop animation.
  95029. */
  95030. set: function (flag) {
  95031. this._zoomStopsAnimation = flag;
  95032. },
  95033. enumerable: true,
  95034. configurable: true
  95035. });
  95036. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  95037. /**
  95038. * Gets the transition time when framing the mesh, in milliseconds
  95039. */
  95040. get: function () {
  95041. return this._framingTime;
  95042. },
  95043. /**
  95044. * Sets the transition time when framing the mesh, in milliseconds
  95045. */
  95046. set: function (time) {
  95047. this._framingTime = time;
  95048. },
  95049. enumerable: true,
  95050. configurable: true
  95051. });
  95052. FramingBehavior.prototype.init = function () {
  95053. // Do notihng
  95054. };
  95055. FramingBehavior.prototype.attach = function (camera) {
  95056. var _this = this;
  95057. this._attachedCamera = camera;
  95058. var scene = this._attachedCamera.getScene();
  95059. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  95060. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95061. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95062. _this._isPointerDown = true;
  95063. return;
  95064. }
  95065. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95066. _this._isPointerDown = false;
  95067. }
  95068. });
  95069. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95070. if (mesh) {
  95071. _this.zoomOnMesh(mesh);
  95072. }
  95073. });
  95074. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95075. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95076. _this._applyUserInteraction();
  95077. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  95078. // back to the default position after a given timeout
  95079. _this._maintainCameraAboveGround();
  95080. });
  95081. };
  95082. FramingBehavior.prototype.detach = function () {
  95083. if (!this._attachedCamera) {
  95084. return;
  95085. }
  95086. var scene = this._attachedCamera.getScene();
  95087. if (this._onPrePointerObservableObserver) {
  95088. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95089. }
  95090. if (this._onAfterCheckInputsObserver) {
  95091. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95092. }
  95093. if (this._onMeshTargetChangedObserver) {
  95094. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95095. }
  95096. this._attachedCamera = null;
  95097. };
  95098. /**
  95099. * Targets the given mesh and updates zoom level accordingly.
  95100. * @param mesh The mesh to target.
  95101. * @param radius Optional. If a cached radius position already exists, overrides default.
  95102. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95103. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95104. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95105. */
  95106. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95107. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95108. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95109. mesh.computeWorldMatrix(true);
  95110. var boundingBox = mesh.getBoundingInfo().boundingBox;
  95111. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  95112. };
  95113. /**
  95114. * Targets the given mesh with its children and updates zoom level accordingly.
  95115. * @param mesh The mesh to target.
  95116. * @param radius Optional. If a cached radius position already exists, overrides default.
  95117. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95118. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95119. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95120. */
  95121. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95122. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95123. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95124. mesh.computeWorldMatrix(true);
  95125. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  95126. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  95127. };
  95128. /**
  95129. * Targets the given meshes with their children and updates zoom level accordingly.
  95130. * @param meshes The mesh to target.
  95131. * @param radius Optional. If a cached radius position already exists, overrides default.
  95132. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95133. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95134. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95135. */
  95136. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  95137. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95138. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95139. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  95140. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95141. for (var i = 0; i < meshes.length; i++) {
  95142. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  95143. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  95144. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  95145. }
  95146. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  95147. };
  95148. /**
  95149. * Targets the given mesh and updates zoom level accordingly.
  95150. * @param mesh The mesh to target.
  95151. * @param radius Optional. If a cached radius position already exists, overrides default.
  95152. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95153. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95154. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95155. */
  95156. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  95157. var _this = this;
  95158. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95159. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95160. var zoomTarget;
  95161. if (!this._attachedCamera) {
  95162. return;
  95163. }
  95164. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  95165. var bottom = minimumWorld.y;
  95166. var top = maximumWorld.y;
  95167. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  95168. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  95169. if (focusOnOriginXZ) {
  95170. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  95171. }
  95172. else {
  95173. var centerWorld = minimumWorld.add(radiusWorld);
  95174. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  95175. }
  95176. if (!this._vectorTransition) {
  95177. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  95178. }
  95179. this._betaIsAnimating = true;
  95180. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  95181. if (animatable) {
  95182. this._animatables.push(animatable);
  95183. }
  95184. // sets the radius and lower radius bounds
  95185. // Small delta ensures camera is not always at lower zoom limit.
  95186. var radius = 0;
  95187. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  95188. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95189. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  95190. radius = position;
  95191. }
  95192. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95193. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95194. if (this._attachedCamera.lowerRadiusLimit === null) {
  95195. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  95196. }
  95197. }
  95198. // Set sensibilities
  95199. var extend = maximumWorld.subtract(minimumWorld).length();
  95200. this._attachedCamera.panningSensibility = 5000 / extend;
  95201. this._attachedCamera.wheelPrecision = 100 / radius;
  95202. // transition to new radius
  95203. if (!this._radiusTransition) {
  95204. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95205. }
  95206. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  95207. _this.stopAllAnimations();
  95208. if (onAnimationEnd) {
  95209. onAnimationEnd();
  95210. }
  95211. if (_this._attachedCamera) {
  95212. _this._attachedCamera.storeState();
  95213. }
  95214. });
  95215. if (animatable) {
  95216. this._animatables.push(animatable);
  95217. }
  95218. };
  95219. /**
  95220. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  95221. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  95222. * frustum width.
  95223. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  95224. * to fully enclose the mesh in the viewing frustum.
  95225. */
  95226. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  95227. var size = maximumWorld.subtract(minimumWorld);
  95228. var boxVectorGlobalDiagonal = size.length();
  95229. var frustumSlope = this._getFrustumSlope();
  95230. // Formula for setting distance
  95231. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  95232. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  95233. // Horizon distance
  95234. var radius = radiusWithoutFraming * this._radiusScale;
  95235. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  95236. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  95237. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  95238. var camera = this._attachedCamera;
  95239. if (!camera) {
  95240. return 0;
  95241. }
  95242. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95243. // Don't exceed the requested limit
  95244. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  95245. }
  95246. // Don't exceed the upper radius limit
  95247. if (camera.upperRadiusLimit) {
  95248. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  95249. }
  95250. return distance;
  95251. };
  95252. /**
  95253. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  95254. * is automatically returned to its default position (expected to be above ground plane).
  95255. */
  95256. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  95257. var _this = this;
  95258. if (this._elevationReturnTime < 0) {
  95259. return;
  95260. }
  95261. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  95262. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  95263. var limitBeta = Math.PI * 0.5;
  95264. // Bring the camera back up if below the ground plane
  95265. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  95266. this._betaIsAnimating = true;
  95267. //Transition to new position
  95268. this.stopAllAnimations();
  95269. if (!this._betaTransition) {
  95270. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95271. }
  95272. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  95273. _this._clearAnimationLocks();
  95274. _this.stopAllAnimations();
  95275. });
  95276. if (animatabe) {
  95277. this._animatables.push(animatabe);
  95278. }
  95279. }
  95280. };
  95281. /**
  95282. * Returns the frustum slope based on the canvas ratio and camera FOV
  95283. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  95284. */
  95285. FramingBehavior.prototype._getFrustumSlope = function () {
  95286. // Calculate the viewport ratio
  95287. // Aspect Ratio is Height/Width.
  95288. var camera = this._attachedCamera;
  95289. if (!camera) {
  95290. return BABYLON.Vector2.Zero();
  95291. }
  95292. var engine = camera.getScene().getEngine();
  95293. var aspectRatio = engine.getAspectRatio(camera);
  95294. // Camera FOV is the vertical field of view (top-bottom) in radians.
  95295. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  95296. var frustumSlopeY = Math.tan(camera.fov / 2);
  95297. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  95298. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  95299. // along the forward vector.
  95300. var frustumSlopeX = frustumSlopeY * aspectRatio;
  95301. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  95302. };
  95303. /**
  95304. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  95305. */
  95306. FramingBehavior.prototype._clearAnimationLocks = function () {
  95307. this._betaIsAnimating = false;
  95308. };
  95309. /**
  95310. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95311. */
  95312. FramingBehavior.prototype._applyUserInteraction = function () {
  95313. if (this.isUserIsMoving) {
  95314. this._lastInteractionTime = BABYLON.Tools.Now;
  95315. this.stopAllAnimations();
  95316. this._clearAnimationLocks();
  95317. }
  95318. };
  95319. /**
  95320. * Stops and removes all animations that have been applied to the camera
  95321. */
  95322. FramingBehavior.prototype.stopAllAnimations = function () {
  95323. if (this._attachedCamera) {
  95324. this._attachedCamera.animations = [];
  95325. }
  95326. while (this._animatables.length) {
  95327. if (this._animatables[0]) {
  95328. this._animatables[0].onAnimationEnd = null;
  95329. this._animatables[0].stop();
  95330. }
  95331. this._animatables.shift();
  95332. }
  95333. };
  95334. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  95335. /**
  95336. * Gets a value indicating if the user is moving the camera
  95337. */
  95338. get: function () {
  95339. if (!this._attachedCamera) {
  95340. return false;
  95341. }
  95342. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95343. this._attachedCamera.inertialBetaOffset !== 0 ||
  95344. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95345. this._attachedCamera.inertialPanningX !== 0 ||
  95346. this._attachedCamera.inertialPanningY !== 0 ||
  95347. this._isPointerDown;
  95348. },
  95349. enumerable: true,
  95350. configurable: true
  95351. });
  95352. /**
  95353. * The easing function used by animations
  95354. */
  95355. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  95356. /**
  95357. * The easing mode used by animations
  95358. */
  95359. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  95360. // Statics
  95361. /**
  95362. * The camera can move all the way towards the mesh.
  95363. */
  95364. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95365. /**
  95366. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95367. */
  95368. FramingBehavior.FitFrustumSidesMode = 1;
  95369. return FramingBehavior;
  95370. }());
  95371. BABYLON.FramingBehavior = FramingBehavior;
  95372. })(BABYLON || (BABYLON = {}));
  95373. //# sourceMappingURL=babylon.framingBehavior.js.map
  95374. var BABYLON;
  95375. (function (BABYLON) {
  95376. /**
  95377. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95378. */
  95379. var BouncingBehavior = /** @class */ (function () {
  95380. function BouncingBehavior() {
  95381. /**
  95382. * The duration of the animation, in milliseconds
  95383. */
  95384. this.transitionDuration = 450;
  95385. /**
  95386. * Length of the distance animated by the transition when lower radius is reached
  95387. */
  95388. this.lowerRadiusTransitionRange = 2;
  95389. /**
  95390. * Length of the distance animated by the transition when upper radius is reached
  95391. */
  95392. this.upperRadiusTransitionRange = -2;
  95393. this._autoTransitionRange = false;
  95394. // Animations
  95395. this._radiusIsAnimating = false;
  95396. this._radiusBounceTransition = null;
  95397. this._animatables = new Array();
  95398. }
  95399. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95400. get: function () {
  95401. return "Bouncing";
  95402. },
  95403. enumerable: true,
  95404. configurable: true
  95405. });
  95406. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95407. /**
  95408. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95409. */
  95410. get: function () {
  95411. return this._autoTransitionRange;
  95412. },
  95413. /**
  95414. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95415. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95416. */
  95417. set: function (value) {
  95418. var _this = this;
  95419. if (this._autoTransitionRange === value) {
  95420. return;
  95421. }
  95422. this._autoTransitionRange = value;
  95423. var camera = this._attachedCamera;
  95424. if (!camera) {
  95425. return;
  95426. }
  95427. if (value) {
  95428. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95429. if (!mesh) {
  95430. return;
  95431. }
  95432. mesh.computeWorldMatrix(true);
  95433. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95434. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95435. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95436. });
  95437. }
  95438. else if (this._onMeshTargetChangedObserver) {
  95439. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95440. }
  95441. },
  95442. enumerable: true,
  95443. configurable: true
  95444. });
  95445. BouncingBehavior.prototype.init = function () {
  95446. // Do notihng
  95447. };
  95448. BouncingBehavior.prototype.attach = function (camera) {
  95449. var _this = this;
  95450. this._attachedCamera = camera;
  95451. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95452. if (!_this._attachedCamera) {
  95453. return;
  95454. }
  95455. // Add the bounce animation to the lower radius limit
  95456. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95457. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95458. }
  95459. // Add the bounce animation to the upper radius limit
  95460. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95461. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95462. }
  95463. });
  95464. };
  95465. BouncingBehavior.prototype.detach = function () {
  95466. if (!this._attachedCamera) {
  95467. return;
  95468. }
  95469. if (this._onAfterCheckInputsObserver) {
  95470. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95471. }
  95472. if (this._onMeshTargetChangedObserver) {
  95473. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95474. }
  95475. this._attachedCamera = null;
  95476. };
  95477. /**
  95478. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95479. * @param radiusLimit The limit to check against.
  95480. * @return Bool to indicate if at limit.
  95481. */
  95482. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95483. if (!this._attachedCamera) {
  95484. return false;
  95485. }
  95486. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95487. return true;
  95488. }
  95489. return false;
  95490. };
  95491. /**
  95492. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95493. * @param radiusDelta The delta by which to animate to. Can be negative.
  95494. */
  95495. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95496. var _this = this;
  95497. if (!this._attachedCamera) {
  95498. return;
  95499. }
  95500. if (!this._radiusBounceTransition) {
  95501. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95502. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95503. }
  95504. // Prevent zoom until bounce has completed
  95505. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95506. this._attachedCamera.wheelPrecision = Infinity;
  95507. this._attachedCamera.inertialRadiusOffset = 0;
  95508. // Animate to the radius limit
  95509. this.stopAllAnimations();
  95510. this._radiusIsAnimating = true;
  95511. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95512. if (animatable) {
  95513. this._animatables.push(animatable);
  95514. }
  95515. };
  95516. /**
  95517. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95518. */
  95519. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95520. this._radiusIsAnimating = false;
  95521. if (this._attachedCamera) {
  95522. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95523. }
  95524. };
  95525. /**
  95526. * Stops and removes all animations that have been applied to the camera
  95527. */
  95528. BouncingBehavior.prototype.stopAllAnimations = function () {
  95529. if (this._attachedCamera) {
  95530. this._attachedCamera.animations = [];
  95531. }
  95532. while (this._animatables.length) {
  95533. this._animatables[0].onAnimationEnd = null;
  95534. this._animatables[0].stop();
  95535. this._animatables.shift();
  95536. }
  95537. };
  95538. /**
  95539. * The easing function used by animations
  95540. */
  95541. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95542. /**
  95543. * The easing mode used by animations
  95544. */
  95545. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95546. return BouncingBehavior;
  95547. }());
  95548. BABYLON.BouncingBehavior = BouncingBehavior;
  95549. })(BABYLON || (BABYLON = {}));
  95550. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95551. var BABYLON;
  95552. (function (BABYLON) {
  95553. var AutoRotationBehavior = /** @class */ (function () {
  95554. function AutoRotationBehavior() {
  95555. this._zoomStopsAnimation = false;
  95556. this._idleRotationSpeed = 0.05;
  95557. this._idleRotationWaitTime = 2000;
  95558. this._idleRotationSpinupTime = 2000;
  95559. this._isPointerDown = false;
  95560. this._lastFrameTime = null;
  95561. this._lastInteractionTime = -Infinity;
  95562. this._cameraRotationSpeed = 0;
  95563. this._lastFrameRadius = 0;
  95564. }
  95565. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95566. get: function () {
  95567. return "AutoRotation";
  95568. },
  95569. enumerable: true,
  95570. configurable: true
  95571. });
  95572. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95573. /**
  95574. * Gets the flag that indicates if user zooming should stop animation.
  95575. */
  95576. get: function () {
  95577. return this._zoomStopsAnimation;
  95578. },
  95579. /**
  95580. * Sets the flag that indicates if user zooming should stop animation.
  95581. */
  95582. set: function (flag) {
  95583. this._zoomStopsAnimation = flag;
  95584. },
  95585. enumerable: true,
  95586. configurable: true
  95587. });
  95588. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95589. /**
  95590. * Gets the default speed at which the camera rotates around the model.
  95591. */
  95592. get: function () {
  95593. return this._idleRotationSpeed;
  95594. },
  95595. /**
  95596. * Sets the default speed at which the camera rotates around the model.
  95597. */
  95598. set: function (speed) {
  95599. this._idleRotationSpeed = speed;
  95600. },
  95601. enumerable: true,
  95602. configurable: true
  95603. });
  95604. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95605. /**
  95606. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95607. */
  95608. get: function () {
  95609. return this._idleRotationWaitTime;
  95610. },
  95611. /**
  95612. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95613. */
  95614. set: function (time) {
  95615. this._idleRotationWaitTime = time;
  95616. },
  95617. enumerable: true,
  95618. configurable: true
  95619. });
  95620. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95621. /**
  95622. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95623. */
  95624. get: function () {
  95625. return this._idleRotationSpinupTime;
  95626. },
  95627. /**
  95628. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95629. */
  95630. set: function (time) {
  95631. this._idleRotationSpinupTime = time;
  95632. },
  95633. enumerable: true,
  95634. configurable: true
  95635. });
  95636. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95637. /**
  95638. * Gets a value indicating if the camera is currently rotating because of this behavior
  95639. */
  95640. get: function () {
  95641. return Math.abs(this._cameraRotationSpeed) > 0;
  95642. },
  95643. enumerable: true,
  95644. configurable: true
  95645. });
  95646. AutoRotationBehavior.prototype.init = function () {
  95647. // Do notihng
  95648. };
  95649. AutoRotationBehavior.prototype.attach = function (camera) {
  95650. var _this = this;
  95651. this._attachedCamera = camera;
  95652. var scene = this._attachedCamera.getScene();
  95653. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95654. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95655. _this._isPointerDown = true;
  95656. return;
  95657. }
  95658. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95659. _this._isPointerDown = false;
  95660. }
  95661. });
  95662. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95663. var now = BABYLON.Tools.Now;
  95664. var dt = 0;
  95665. if (_this._lastFrameTime != null) {
  95666. dt = now - _this._lastFrameTime;
  95667. }
  95668. _this._lastFrameTime = now;
  95669. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95670. _this._applyUserInteraction();
  95671. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95672. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95673. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95674. // Step camera rotation by rotation speed
  95675. if (_this._attachedCamera) {
  95676. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95677. }
  95678. });
  95679. };
  95680. AutoRotationBehavior.prototype.detach = function () {
  95681. if (!this._attachedCamera) {
  95682. return;
  95683. }
  95684. var scene = this._attachedCamera.getScene();
  95685. if (this._onPrePointerObservableObserver) {
  95686. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95687. }
  95688. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95689. this._attachedCamera = null;
  95690. };
  95691. /**
  95692. * Returns true if user is scrolling.
  95693. * @return true if user is scrolling.
  95694. */
  95695. AutoRotationBehavior.prototype._userIsZooming = function () {
  95696. if (!this._attachedCamera) {
  95697. return false;
  95698. }
  95699. return this._attachedCamera.inertialRadiusOffset !== 0;
  95700. };
  95701. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95702. if (!this._attachedCamera) {
  95703. return false;
  95704. }
  95705. var zoomHasHitLimit = false;
  95706. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95707. zoomHasHitLimit = true;
  95708. }
  95709. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95710. this._lastFrameRadius = this._attachedCamera.radius;
  95711. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95712. };
  95713. /**
  95714. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95715. */
  95716. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95717. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95718. this._lastInteractionTime = BABYLON.Tools.Now;
  95719. }
  95720. };
  95721. // Tools
  95722. AutoRotationBehavior.prototype._userIsMoving = function () {
  95723. if (!this._attachedCamera) {
  95724. return false;
  95725. }
  95726. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95727. this._attachedCamera.inertialBetaOffset !== 0 ||
  95728. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95729. this._attachedCamera.inertialPanningX !== 0 ||
  95730. this._attachedCamera.inertialPanningY !== 0 ||
  95731. this._isPointerDown;
  95732. };
  95733. return AutoRotationBehavior;
  95734. }());
  95735. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95736. })(BABYLON || (BABYLON = {}));
  95737. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95738. var BABYLON;
  95739. (function (BABYLON) {
  95740. /**
  95741. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95742. */
  95743. var PointerDragBehavior = /** @class */ (function () {
  95744. /**
  95745. * Creates a pointer drag behavior that can be attached to a mesh
  95746. * @param options The drag axis or normal of the plane that will be dragged across. pointerObservableScene can be used to listen to drag events from another scene(eg. if the attached mesh is in an overlay scene).
  95747. */
  95748. function PointerDragBehavior(options) {
  95749. this.options = options;
  95750. this._draggingID = -1;
  95751. /**
  95752. * Fires each time the attached mesh is dragged with the pointer
  95753. */
  95754. this.onDragObservable = new BABYLON.Observable();
  95755. /**
  95756. * Fires each time a drag begins (eg. mouse down on mesh)
  95757. */
  95758. this.onDragStartObservable = new BABYLON.Observable();
  95759. /**
  95760. * Fires each time a drag ends (eg. mouse release after drag)
  95761. */
  95762. this.onDragEndObservable = new BABYLON.Observable();
  95763. /**
  95764. * If the attached mesh should be moved when dragged
  95765. */
  95766. this.moveAttached = true;
  95767. /**
  95768. * Mesh with the position where the drag plane should be placed
  95769. */
  95770. this._dragPlaneParent = null;
  95771. var optionCount = 0;
  95772. if (options.dragAxis) {
  95773. optionCount++;
  95774. }
  95775. if (options.dragPlaneNormal) {
  95776. optionCount++;
  95777. }
  95778. if (optionCount > 1) {
  95779. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95780. }
  95781. if (optionCount < 1) {
  95782. throw "At least one drag mode option must be specified";
  95783. }
  95784. }
  95785. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95786. /**
  95787. * The name of the behavior
  95788. */
  95789. get: function () {
  95790. return "PointerDrag";
  95791. },
  95792. enumerable: true,
  95793. configurable: true
  95794. });
  95795. /**
  95796. * Initializes the behavior
  95797. */
  95798. PointerDragBehavior.prototype.init = function () { };
  95799. /**
  95800. * Attaches the drag behavior the passed in mesh
  95801. * @param ownerNode The mesh that will be dragged around once attached
  95802. */
  95803. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95804. var _this = this;
  95805. this._scene = ownerNode.getScene();
  95806. if (!this.options.pointerObservableScene) {
  95807. this.options.pointerObservableScene = this._scene;
  95808. }
  95809. this._attachedNode = ownerNode;
  95810. // Initialize drag plane to not interfere with existing scene
  95811. if (!PointerDragBehavior._planeScene) {
  95812. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95813. this._scene.getEngine().scenes.pop();
  95814. }
  95815. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95816. // State of the drag
  95817. var dragging = false;
  95818. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  95819. var delta = new BABYLON.Vector3(0, 0, 0);
  95820. var pickPredicate = function (m) {
  95821. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95822. };
  95823. this._pointerObserver = this.options.pointerObservableScene.onPrePointerObservable.add(function (pointerInfoPre, eventState) {
  95824. // Check if attached mesh is picked
  95825. var pickInfo = pointerInfoPre.ray ? _this._scene.pickWithRay(pointerInfoPre.ray, pickPredicate) : _this._scene.pick(_this._scene.pointerX, _this._scene.pointerY, pickPredicate);
  95826. if (pickInfo) {
  95827. pickInfo.ray = pointerInfoPre.ray;
  95828. if (!pickInfo.ray) {
  95829. pickInfo.ray = _this.options.pointerObservableScene.createPickingRay(_this._scene.pointerX, _this._scene.pointerY, BABYLON.Matrix.Identity(), _this._scene.activeCamera);
  95830. }
  95831. if (pickInfo.hit) {
  95832. eventState.skipNextObservers = true;
  95833. }
  95834. }
  95835. if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95836. if (!dragging && pickInfo && pickInfo.hit && pickInfo.pickedMesh && pickInfo.ray) {
  95837. _this._updateDragPlanePosition(pickInfo.ray);
  95838. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95839. if (pickedPoint) {
  95840. dragging = true;
  95841. _this._draggingID = pointerInfoPre.event.pointerId;
  95842. lastPosition.copyFrom(pickedPoint);
  95843. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  95844. }
  95845. }
  95846. }
  95847. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERUP) {
  95848. if (_this._draggingID == pointerInfoPre.event.pointerId) {
  95849. dragging = false;
  95850. _this._draggingID = -1;
  95851. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  95852. }
  95853. }
  95854. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95855. if (_this._draggingID == pointerInfoPre.event.pointerId && dragging && pickInfo && pickInfo.ray) {
  95856. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95857. _this._updateDragPlanePosition(pickInfo.ray);
  95858. if (pickedPoint) {
  95859. // depending on the drag mode option drag accordingly
  95860. if (_this.options.dragAxis) {
  95861. //get the closest point on the dragaxis from the selected mesh to the picked point location
  95862. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  95863. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  95864. }
  95865. else {
  95866. pickedPoint.subtractToRef(lastPosition, delta);
  95867. }
  95868. if (_this.moveAttached) {
  95869. _this._attachedNode.position.addInPlace(delta);
  95870. }
  95871. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  95872. lastPosition.copyFrom(pickedPoint);
  95873. }
  95874. }
  95875. }
  95876. });
  95877. };
  95878. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95879. var _this = this;
  95880. if (!ray) {
  95881. return null;
  95882. }
  95883. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95884. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95885. return pickResult.pickedPoint;
  95886. }
  95887. else {
  95888. return null;
  95889. }
  95890. };
  95891. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95892. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  95893. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  95894. if (this.options.dragAxis) {
  95895. var camPos = ray.origin;
  95896. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95897. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  95898. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  95899. // Get perpendicular line from direction to camera and drag axis
  95900. var lineA = pointB.subtract(pointA);
  95901. var lineB = pointC.subtract(pointA);
  95902. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  95903. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95904. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  95905. this._dragPlane.position.copyFrom(pointA);
  95906. this._dragPlane.lookAt(pointA.add(norm));
  95907. }
  95908. else if (this.options.dragPlaneNormal) {
  95909. this._dragPlane.position.copyFrom(pointA);
  95910. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  95911. }
  95912. this._dragPlane.computeWorldMatrix(true);
  95913. };
  95914. /**
  95915. * Detaches the behavior from the mesh
  95916. */
  95917. PointerDragBehavior.prototype.detach = function () {
  95918. if (this._pointerObserver) {
  95919. this._scene.onPrePointerObservable.remove(this._pointerObserver);
  95920. }
  95921. };
  95922. return PointerDragBehavior;
  95923. }());
  95924. BABYLON.PointerDragBehavior = PointerDragBehavior;
  95925. })(BABYLON || (BABYLON = {}));
  95926. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  95927. var BABYLON;
  95928. (function (BABYLON) {
  95929. var NullEngineOptions = /** @class */ (function () {
  95930. function NullEngineOptions() {
  95931. this.renderWidth = 512;
  95932. this.renderHeight = 256;
  95933. this.textureSize = 512;
  95934. this.deterministicLockstep = false;
  95935. this.lockstepMaxSteps = 4;
  95936. }
  95937. return NullEngineOptions;
  95938. }());
  95939. BABYLON.NullEngineOptions = NullEngineOptions;
  95940. /**
  95941. * The null engine class provides support for headless version of babylon.js.
  95942. * This can be used in server side scenario or for testing purposes
  95943. */
  95944. var NullEngine = /** @class */ (function (_super) {
  95945. __extends(NullEngine, _super);
  95946. function NullEngine(options) {
  95947. if (options === void 0) { options = new NullEngineOptions(); }
  95948. var _this = _super.call(this, null) || this;
  95949. if (options.deterministicLockstep === undefined) {
  95950. options.deterministicLockstep = false;
  95951. }
  95952. if (options.lockstepMaxSteps === undefined) {
  95953. options.lockstepMaxSteps = 4;
  95954. }
  95955. _this._options = options;
  95956. // Init caps
  95957. // We consider we are on a webgl1 capable device
  95958. _this._caps = new BABYLON.EngineCapabilities();
  95959. _this._caps.maxTexturesImageUnits = 16;
  95960. _this._caps.maxVertexTextureImageUnits = 16;
  95961. _this._caps.maxTextureSize = 512;
  95962. _this._caps.maxCubemapTextureSize = 512;
  95963. _this._caps.maxRenderTextureSize = 512;
  95964. _this._caps.maxVertexAttribs = 16;
  95965. _this._caps.maxVaryingVectors = 16;
  95966. _this._caps.maxFragmentUniformVectors = 16;
  95967. _this._caps.maxVertexUniformVectors = 16;
  95968. // Extensions
  95969. _this._caps.standardDerivatives = false;
  95970. _this._caps.astc = null;
  95971. _this._caps.s3tc = null;
  95972. _this._caps.pvrtc = null;
  95973. _this._caps.etc1 = null;
  95974. _this._caps.etc2 = null;
  95975. _this._caps.textureAnisotropicFilterExtension = null;
  95976. _this._caps.maxAnisotropy = 0;
  95977. _this._caps.uintIndices = false;
  95978. _this._caps.fragmentDepthSupported = false;
  95979. _this._caps.highPrecisionShaderSupported = true;
  95980. _this._caps.colorBufferFloat = false;
  95981. _this._caps.textureFloat = false;
  95982. _this._caps.textureFloatLinearFiltering = false;
  95983. _this._caps.textureFloatRender = false;
  95984. _this._caps.textureHalfFloat = false;
  95985. _this._caps.textureHalfFloatLinearFiltering = false;
  95986. _this._caps.textureHalfFloatRender = false;
  95987. _this._caps.textureLOD = false;
  95988. _this._caps.drawBuffersExtension = false;
  95989. _this._caps.depthTextureExtension = false;
  95990. _this._caps.vertexArrayObject = false;
  95991. _this._caps.instancedArrays = false;
  95992. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95993. // Wrappers
  95994. if (typeof URL === "undefined") {
  95995. URL = {
  95996. createObjectURL: function () { },
  95997. revokeObjectURL: function () { }
  95998. };
  95999. }
  96000. if (typeof Blob === "undefined") {
  96001. Blob = function () { };
  96002. }
  96003. return _this;
  96004. }
  96005. NullEngine.prototype.isDeterministicLockStep = function () {
  96006. return this._options.deterministicLockstep;
  96007. };
  96008. NullEngine.prototype.getLockstepMaxSteps = function () {
  96009. return this._options.lockstepMaxSteps;
  96010. };
  96011. NullEngine.prototype.getHardwareScalingLevel = function () {
  96012. return 1.0;
  96013. };
  96014. NullEngine.prototype.createVertexBuffer = function (vertices) {
  96015. return {
  96016. capacity: 0,
  96017. references: 1,
  96018. is32Bits: false
  96019. };
  96020. };
  96021. NullEngine.prototype.createIndexBuffer = function (indices) {
  96022. return {
  96023. capacity: 0,
  96024. references: 1,
  96025. is32Bits: false
  96026. };
  96027. };
  96028. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  96029. if (stencil === void 0) { stencil = false; }
  96030. };
  96031. NullEngine.prototype.getRenderWidth = function (useScreen) {
  96032. if (useScreen === void 0) { useScreen = false; }
  96033. if (!useScreen && this._currentRenderTarget) {
  96034. return this._currentRenderTarget.width;
  96035. }
  96036. return this._options.renderWidth;
  96037. };
  96038. NullEngine.prototype.getRenderHeight = function (useScreen) {
  96039. if (useScreen === void 0) { useScreen = false; }
  96040. if (!useScreen && this._currentRenderTarget) {
  96041. return this._currentRenderTarget.height;
  96042. }
  96043. return this._options.renderHeight;
  96044. };
  96045. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  96046. this._cachedViewport = viewport;
  96047. };
  96048. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  96049. return {
  96050. transformFeedback: null,
  96051. __SPECTOR_rebuildProgram: null
  96052. };
  96053. };
  96054. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  96055. return [];
  96056. };
  96057. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  96058. return [];
  96059. };
  96060. NullEngine.prototype.bindSamplers = function (effect) {
  96061. this._currentEffect = null;
  96062. };
  96063. NullEngine.prototype.enableEffect = function (effect) {
  96064. this._currentEffect = effect;
  96065. if (effect.onBind) {
  96066. effect.onBind(effect);
  96067. }
  96068. effect.onBindObservable.notifyObservers(effect);
  96069. };
  96070. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  96071. if (zOffset === void 0) { zOffset = 0; }
  96072. if (reverseSide === void 0) { reverseSide = false; }
  96073. };
  96074. NullEngine.prototype.setIntArray = function (uniform, array) {
  96075. };
  96076. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  96077. };
  96078. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  96079. };
  96080. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  96081. };
  96082. NullEngine.prototype.setFloatArray = function (uniform, array) {
  96083. };
  96084. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  96085. };
  96086. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  96087. };
  96088. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  96089. };
  96090. NullEngine.prototype.setArray = function (uniform, array) {
  96091. };
  96092. NullEngine.prototype.setArray2 = function (uniform, array) {
  96093. };
  96094. NullEngine.prototype.setArray3 = function (uniform, array) {
  96095. };
  96096. NullEngine.prototype.setArray4 = function (uniform, array) {
  96097. };
  96098. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  96099. };
  96100. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  96101. };
  96102. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  96103. };
  96104. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  96105. };
  96106. NullEngine.prototype.setFloat = function (uniform, value) {
  96107. };
  96108. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  96109. };
  96110. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  96111. };
  96112. NullEngine.prototype.setBool = function (uniform, bool) {
  96113. };
  96114. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  96115. };
  96116. NullEngine.prototype.setColor3 = function (uniform, color3) {
  96117. };
  96118. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  96119. };
  96120. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  96121. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  96122. if (this._alphaMode === mode) {
  96123. return;
  96124. }
  96125. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  96126. if (!noDepthWriteChange) {
  96127. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  96128. }
  96129. this._alphaMode = mode;
  96130. };
  96131. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  96132. };
  96133. NullEngine.prototype.wipeCaches = function (bruteForce) {
  96134. if (this.preventCacheWipeBetweenFrames) {
  96135. return;
  96136. }
  96137. this.resetTextureCache();
  96138. this._currentEffect = null;
  96139. if (bruteForce) {
  96140. this._currentProgram = null;
  96141. this._stencilState.reset();
  96142. this._depthCullingState.reset();
  96143. this._alphaState.reset();
  96144. }
  96145. this._cachedVertexBuffers = null;
  96146. this._cachedIndexBuffer = null;
  96147. this._cachedEffectForVertexBuffers = null;
  96148. };
  96149. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  96150. };
  96151. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  96152. };
  96153. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  96154. };
  96155. NullEngine.prototype._createTexture = function () {
  96156. return {};
  96157. };
  96158. NullEngine.prototype._releaseTexture = function (texture) {
  96159. };
  96160. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  96161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96162. if (onLoad === void 0) { onLoad = null; }
  96163. if (onError === void 0) { onError = null; }
  96164. if (buffer === void 0) { buffer = null; }
  96165. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  96166. var url = String(urlArg);
  96167. texture.url = url;
  96168. texture.generateMipMaps = !noMipmap;
  96169. texture.samplingMode = samplingMode;
  96170. texture.invertY = invertY;
  96171. texture.baseWidth = this._options.textureSize;
  96172. texture.baseHeight = this._options.textureSize;
  96173. texture.width = this._options.textureSize;
  96174. texture.height = this._options.textureSize;
  96175. if (format) {
  96176. texture.format = format;
  96177. }
  96178. texture.isReady = true;
  96179. if (onLoad) {
  96180. onLoad();
  96181. }
  96182. this._internalTexturesCache.push(texture);
  96183. return texture;
  96184. };
  96185. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  96186. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  96187. if (options !== undefined && typeof options === "object") {
  96188. fullOptions.generateMipMaps = options.generateMipMaps;
  96189. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  96190. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  96191. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  96192. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  96193. }
  96194. else {
  96195. fullOptions.generateMipMaps = options;
  96196. fullOptions.generateDepthBuffer = true;
  96197. fullOptions.generateStencilBuffer = false;
  96198. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96199. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  96200. }
  96201. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  96202. var width = size.width || size;
  96203. var height = size.height || size;
  96204. texture._depthStencilBuffer = {};
  96205. texture._framebuffer = {};
  96206. texture.baseWidth = width;
  96207. texture.baseHeight = height;
  96208. texture.width = width;
  96209. texture.height = height;
  96210. texture.isReady = true;
  96211. texture.samples = 1;
  96212. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  96213. texture.samplingMode = fullOptions.samplingMode;
  96214. texture.type = fullOptions.type;
  96215. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  96216. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  96217. this._internalTexturesCache.push(texture);
  96218. return texture;
  96219. };
  96220. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  96221. texture.samplingMode = samplingMode;
  96222. };
  96223. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  96224. if (this._currentRenderTarget) {
  96225. this.unBindFramebuffer(this._currentRenderTarget);
  96226. }
  96227. this._currentRenderTarget = texture;
  96228. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  96229. if (this._cachedViewport && !forceFullscreenViewport) {
  96230. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  96231. }
  96232. };
  96233. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  96234. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  96235. this._currentRenderTarget = null;
  96236. if (onBeforeUnbind) {
  96237. if (texture._MSAAFramebuffer) {
  96238. this._currentFramebuffer = texture._framebuffer;
  96239. }
  96240. onBeforeUnbind();
  96241. }
  96242. this._currentFramebuffer = null;
  96243. };
  96244. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  96245. var vbo = {
  96246. capacity: 1,
  96247. references: 1,
  96248. is32Bits: false
  96249. };
  96250. return vbo;
  96251. };
  96252. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  96253. if (offset === void 0) { offset = 0; }
  96254. };
  96255. /**
  96256. * Updates a dynamic vertex buffer.
  96257. * @param vertexBuffer the vertex buffer to update
  96258. * @param data the data used to update the vertex buffer
  96259. * @param byteOffset the byte offset of the data (optional)
  96260. * @param byteLength the byte length of the data (optional)
  96261. */
  96262. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  96263. };
  96264. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  96265. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  96266. this._boundTexturesCache[this._activeChannel] = texture;
  96267. }
  96268. };
  96269. NullEngine.prototype._bindTexture = function (channel, texture) {
  96270. if (channel < 0) {
  96271. return;
  96272. }
  96273. this._bindTextureDirectly(0, texture);
  96274. };
  96275. NullEngine.prototype._releaseBuffer = function (buffer) {
  96276. buffer.references--;
  96277. if (buffer.references === 0) {
  96278. return true;
  96279. }
  96280. return false;
  96281. };
  96282. NullEngine.prototype.releaseEffects = function () {
  96283. };
  96284. return NullEngine;
  96285. }(BABYLON.Engine));
  96286. BABYLON.NullEngine = NullEngine;
  96287. })(BABYLON || (BABYLON = {}));
  96288. //# sourceMappingURL=babylon.nullEngine.js.map
  96289. var BABYLON;
  96290. (function (BABYLON) {
  96291. /**
  96292. * This class can be used to get instrumentation data from a Babylon engine
  96293. */
  96294. var EngineInstrumentation = /** @class */ (function () {
  96295. function EngineInstrumentation(engine) {
  96296. this.engine = engine;
  96297. this._captureGPUFrameTime = false;
  96298. this._gpuFrameTime = new BABYLON.PerfCounter();
  96299. this._captureShaderCompilationTime = false;
  96300. this._shaderCompilationTime = new BABYLON.PerfCounter();
  96301. // Observers
  96302. this._onBeginFrameObserver = null;
  96303. this._onEndFrameObserver = null;
  96304. this._onBeforeShaderCompilationObserver = null;
  96305. this._onAfterShaderCompilationObserver = null;
  96306. }
  96307. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  96308. // Properties
  96309. /**
  96310. * Gets the perf counter used for GPU frame time
  96311. */
  96312. get: function () {
  96313. return this._gpuFrameTime;
  96314. },
  96315. enumerable: true,
  96316. configurable: true
  96317. });
  96318. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  96319. /**
  96320. * Gets the GPU frame time capture status
  96321. */
  96322. get: function () {
  96323. return this._captureGPUFrameTime;
  96324. },
  96325. /**
  96326. * Enable or disable the GPU frame time capture
  96327. */
  96328. set: function (value) {
  96329. var _this = this;
  96330. if (value === this._captureGPUFrameTime) {
  96331. return;
  96332. }
  96333. this._captureGPUFrameTime = value;
  96334. if (value) {
  96335. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  96336. if (!_this._gpuFrameTimeToken) {
  96337. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  96338. }
  96339. });
  96340. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  96341. if (!_this._gpuFrameTimeToken) {
  96342. return;
  96343. }
  96344. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  96345. if (time > -1) {
  96346. _this._gpuFrameTimeToken = null;
  96347. _this._gpuFrameTime.fetchNewFrame();
  96348. _this._gpuFrameTime.addCount(time, true);
  96349. }
  96350. });
  96351. }
  96352. else {
  96353. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96354. this._onBeginFrameObserver = null;
  96355. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96356. this._onEndFrameObserver = null;
  96357. }
  96358. },
  96359. enumerable: true,
  96360. configurable: true
  96361. });
  96362. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  96363. /**
  96364. * Gets the perf counter used for shader compilation time
  96365. */
  96366. get: function () {
  96367. return this._shaderCompilationTime;
  96368. },
  96369. enumerable: true,
  96370. configurable: true
  96371. });
  96372. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  96373. /**
  96374. * Gets the shader compilation time capture status
  96375. */
  96376. get: function () {
  96377. return this._captureShaderCompilationTime;
  96378. },
  96379. /**
  96380. * Enable or disable the shader compilation time capture
  96381. */
  96382. set: function (value) {
  96383. var _this = this;
  96384. if (value === this._captureShaderCompilationTime) {
  96385. return;
  96386. }
  96387. this._captureShaderCompilationTime = value;
  96388. if (value) {
  96389. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  96390. _this._shaderCompilationTime.fetchNewFrame();
  96391. _this._shaderCompilationTime.beginMonitoring();
  96392. });
  96393. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  96394. _this._shaderCompilationTime.endMonitoring();
  96395. });
  96396. }
  96397. else {
  96398. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96399. this._onBeforeShaderCompilationObserver = null;
  96400. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96401. this._onAfterShaderCompilationObserver = null;
  96402. }
  96403. },
  96404. enumerable: true,
  96405. configurable: true
  96406. });
  96407. EngineInstrumentation.prototype.dispose = function () {
  96408. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96409. this._onBeginFrameObserver = null;
  96410. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96411. this._onEndFrameObserver = null;
  96412. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96413. this._onBeforeShaderCompilationObserver = null;
  96414. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96415. this._onAfterShaderCompilationObserver = null;
  96416. this.engine = null;
  96417. };
  96418. return EngineInstrumentation;
  96419. }());
  96420. BABYLON.EngineInstrumentation = EngineInstrumentation;
  96421. })(BABYLON || (BABYLON = {}));
  96422. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  96423. var BABYLON;
  96424. (function (BABYLON) {
  96425. /**
  96426. * This class can be used to get instrumentation data from a Babylon engine
  96427. */
  96428. var SceneInstrumentation = /** @class */ (function () {
  96429. function SceneInstrumentation(scene) {
  96430. var _this = this;
  96431. this.scene = scene;
  96432. this._captureActiveMeshesEvaluationTime = false;
  96433. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  96434. this._captureRenderTargetsRenderTime = false;
  96435. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  96436. this._captureFrameTime = false;
  96437. this._frameTime = new BABYLON.PerfCounter();
  96438. this._captureRenderTime = false;
  96439. this._renderTime = new BABYLON.PerfCounter();
  96440. this._captureInterFrameTime = false;
  96441. this._interFrameTime = new BABYLON.PerfCounter();
  96442. this._captureParticlesRenderTime = false;
  96443. this._particlesRenderTime = new BABYLON.PerfCounter();
  96444. this._captureSpritesRenderTime = false;
  96445. this._spritesRenderTime = new BABYLON.PerfCounter();
  96446. this._capturePhysicsTime = false;
  96447. this._physicsTime = new BABYLON.PerfCounter();
  96448. this._captureAnimationsTime = false;
  96449. this._animationsTime = new BABYLON.PerfCounter();
  96450. // Observers
  96451. this._onBeforeActiveMeshesEvaluationObserver = null;
  96452. this._onAfterActiveMeshesEvaluationObserver = null;
  96453. this._onBeforeRenderTargetsRenderObserver = null;
  96454. this._onAfterRenderTargetsRenderObserver = null;
  96455. this._onAfterRenderObserver = null;
  96456. this._onBeforeDrawPhaseObserver = null;
  96457. this._onAfterDrawPhaseObserver = null;
  96458. this._onBeforeAnimationsObserver = null;
  96459. this._onBeforeParticlesRenderingObserver = null;
  96460. this._onAfterParticlesRenderingObserver = null;
  96461. this._onBeforeSpritesRenderingObserver = null;
  96462. this._onAfterSpritesRenderingObserver = null;
  96463. this._onBeforePhysicsObserver = null;
  96464. this._onAfterPhysicsObserver = null;
  96465. this._onAfterAnimationsObserver = null;
  96466. // Before render
  96467. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  96468. if (_this._captureActiveMeshesEvaluationTime) {
  96469. _this._activeMeshesEvaluationTime.fetchNewFrame();
  96470. }
  96471. if (_this._captureRenderTargetsRenderTime) {
  96472. _this._renderTargetsRenderTime.fetchNewFrame();
  96473. }
  96474. if (_this._captureFrameTime) {
  96475. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  96476. _this._frameTime.beginMonitoring();
  96477. }
  96478. if (_this._captureInterFrameTime) {
  96479. _this._interFrameTime.endMonitoring();
  96480. }
  96481. if (_this._captureParticlesRenderTime) {
  96482. _this._particlesRenderTime.fetchNewFrame();
  96483. }
  96484. if (_this._captureSpritesRenderTime) {
  96485. _this._spritesRenderTime.fetchNewFrame();
  96486. }
  96487. if (_this._captureAnimationsTime) {
  96488. _this._animationsTime.beginMonitoring();
  96489. }
  96490. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  96491. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  96492. });
  96493. // After render
  96494. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  96495. if (_this._captureFrameTime) {
  96496. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  96497. _this._frameTime.endMonitoring();
  96498. }
  96499. if (_this._captureRenderTime) {
  96500. _this._renderTime.endMonitoring(false);
  96501. }
  96502. if (_this._captureInterFrameTime) {
  96503. _this._interFrameTime.beginMonitoring();
  96504. }
  96505. });
  96506. }
  96507. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  96508. // Properties
  96509. /**
  96510. * Gets the perf counter used for active meshes evaluation time
  96511. */
  96512. get: function () {
  96513. return this._activeMeshesEvaluationTime;
  96514. },
  96515. enumerable: true,
  96516. configurable: true
  96517. });
  96518. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  96519. /**
  96520. * Gets the active meshes evaluation time capture status
  96521. */
  96522. get: function () {
  96523. return this._captureActiveMeshesEvaluationTime;
  96524. },
  96525. /**
  96526. * Enable or disable the active meshes evaluation time capture
  96527. */
  96528. set: function (value) {
  96529. var _this = this;
  96530. if (value === this._captureActiveMeshesEvaluationTime) {
  96531. return;
  96532. }
  96533. this._captureActiveMeshesEvaluationTime = value;
  96534. if (value) {
  96535. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  96536. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  96537. _this._activeMeshesEvaluationTime.beginMonitoring();
  96538. });
  96539. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  96540. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  96541. _this._activeMeshesEvaluationTime.endMonitoring();
  96542. });
  96543. }
  96544. else {
  96545. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96546. this._onBeforeActiveMeshesEvaluationObserver = null;
  96547. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96548. this._onAfterActiveMeshesEvaluationObserver = null;
  96549. }
  96550. },
  96551. enumerable: true,
  96552. configurable: true
  96553. });
  96554. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96555. /**
  96556. * Gets the perf counter used for render targets render time
  96557. */
  96558. get: function () {
  96559. return this._renderTargetsRenderTime;
  96560. },
  96561. enumerable: true,
  96562. configurable: true
  96563. });
  96564. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96565. /**
  96566. * Gets the render targets render time capture status
  96567. */
  96568. get: function () {
  96569. return this._captureRenderTargetsRenderTime;
  96570. },
  96571. /**
  96572. * Enable or disable the render targets render time capture
  96573. */
  96574. set: function (value) {
  96575. var _this = this;
  96576. if (value === this._captureRenderTargetsRenderTime) {
  96577. return;
  96578. }
  96579. this._captureRenderTargetsRenderTime = value;
  96580. if (value) {
  96581. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96582. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96583. _this._renderTargetsRenderTime.beginMonitoring();
  96584. });
  96585. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96586. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96587. _this._renderTargetsRenderTime.endMonitoring(false);
  96588. });
  96589. }
  96590. else {
  96591. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96592. this._onBeforeRenderTargetsRenderObserver = null;
  96593. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96594. this._onAfterRenderTargetsRenderObserver = null;
  96595. }
  96596. },
  96597. enumerable: true,
  96598. configurable: true
  96599. });
  96600. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96601. /**
  96602. * Gets the perf counter used for particles render time
  96603. */
  96604. get: function () {
  96605. return this._particlesRenderTime;
  96606. },
  96607. enumerable: true,
  96608. configurable: true
  96609. });
  96610. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96611. /**
  96612. * Gets the particles render time capture status
  96613. */
  96614. get: function () {
  96615. return this._captureParticlesRenderTime;
  96616. },
  96617. /**
  96618. * Enable or disable the particles render time capture
  96619. */
  96620. set: function (value) {
  96621. var _this = this;
  96622. if (value === this._captureParticlesRenderTime) {
  96623. return;
  96624. }
  96625. this._captureParticlesRenderTime = value;
  96626. if (value) {
  96627. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96628. BABYLON.Tools.StartPerformanceCounter("Particles");
  96629. _this._particlesRenderTime.beginMonitoring();
  96630. });
  96631. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96632. BABYLON.Tools.EndPerformanceCounter("Particles");
  96633. _this._particlesRenderTime.endMonitoring(false);
  96634. });
  96635. }
  96636. else {
  96637. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96638. this._onBeforeParticlesRenderingObserver = null;
  96639. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96640. this._onAfterParticlesRenderingObserver = null;
  96641. }
  96642. },
  96643. enumerable: true,
  96644. configurable: true
  96645. });
  96646. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  96647. /**
  96648. * Gets the perf counter used for sprites render time
  96649. */
  96650. get: function () {
  96651. return this._spritesRenderTime;
  96652. },
  96653. enumerable: true,
  96654. configurable: true
  96655. });
  96656. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  96657. /**
  96658. * Gets the sprites render time capture status
  96659. */
  96660. get: function () {
  96661. return this._captureSpritesRenderTime;
  96662. },
  96663. /**
  96664. * Enable or disable the sprites render time capture
  96665. */
  96666. set: function (value) {
  96667. var _this = this;
  96668. if (value === this._captureSpritesRenderTime) {
  96669. return;
  96670. }
  96671. this._captureSpritesRenderTime = value;
  96672. if (value) {
  96673. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  96674. BABYLON.Tools.StartPerformanceCounter("Sprites");
  96675. _this._spritesRenderTime.beginMonitoring();
  96676. });
  96677. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  96678. BABYLON.Tools.EndPerformanceCounter("Sprites");
  96679. _this._spritesRenderTime.endMonitoring(false);
  96680. });
  96681. }
  96682. else {
  96683. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96684. this._onBeforeSpritesRenderingObserver = null;
  96685. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96686. this._onAfterSpritesRenderingObserver = null;
  96687. }
  96688. },
  96689. enumerable: true,
  96690. configurable: true
  96691. });
  96692. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  96693. /**
  96694. * Gets the perf counter used for physics time
  96695. */
  96696. get: function () {
  96697. return this._physicsTime;
  96698. },
  96699. enumerable: true,
  96700. configurable: true
  96701. });
  96702. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  96703. /**
  96704. * Gets the physics time capture status
  96705. */
  96706. get: function () {
  96707. return this._capturePhysicsTime;
  96708. },
  96709. /**
  96710. * Enable or disable the physics time capture
  96711. */
  96712. set: function (value) {
  96713. var _this = this;
  96714. if (value === this._capturePhysicsTime) {
  96715. return;
  96716. }
  96717. this._capturePhysicsTime = value;
  96718. if (value) {
  96719. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96720. BABYLON.Tools.StartPerformanceCounter("Physics");
  96721. _this._physicsTime.beginMonitoring();
  96722. });
  96723. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96724. BABYLON.Tools.EndPerformanceCounter("Physics");
  96725. _this._physicsTime.endMonitoring();
  96726. });
  96727. }
  96728. else {
  96729. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96730. this._onBeforePhysicsObserver = null;
  96731. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96732. this._onAfterPhysicsObserver = null;
  96733. }
  96734. },
  96735. enumerable: true,
  96736. configurable: true
  96737. });
  96738. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96739. /**
  96740. * Gets the perf counter used for animations time
  96741. */
  96742. get: function () {
  96743. return this._animationsTime;
  96744. },
  96745. enumerable: true,
  96746. configurable: true
  96747. });
  96748. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96749. /**
  96750. * Gets the animations time capture status
  96751. */
  96752. get: function () {
  96753. return this._captureAnimationsTime;
  96754. },
  96755. /**
  96756. * Enable or disable the animations time capture
  96757. */
  96758. set: function (value) {
  96759. var _this = this;
  96760. if (value === this._captureAnimationsTime) {
  96761. return;
  96762. }
  96763. this._captureAnimationsTime = value;
  96764. if (value) {
  96765. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96766. _this._animationsTime.endMonitoring();
  96767. });
  96768. }
  96769. else {
  96770. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96771. this._onAfterAnimationsObserver = null;
  96772. }
  96773. },
  96774. enumerable: true,
  96775. configurable: true
  96776. });
  96777. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96778. /**
  96779. * Gets the perf counter used for frame time capture
  96780. */
  96781. get: function () {
  96782. return this._frameTime;
  96783. },
  96784. enumerable: true,
  96785. configurable: true
  96786. });
  96787. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96788. /**
  96789. * Gets the frame time capture status
  96790. */
  96791. get: function () {
  96792. return this._captureFrameTime;
  96793. },
  96794. /**
  96795. * Enable or disable the frame time capture
  96796. */
  96797. set: function (value) {
  96798. this._captureFrameTime = value;
  96799. },
  96800. enumerable: true,
  96801. configurable: true
  96802. });
  96803. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96804. /**
  96805. * Gets the perf counter used for inter-frames time capture
  96806. */
  96807. get: function () {
  96808. return this._interFrameTime;
  96809. },
  96810. enumerable: true,
  96811. configurable: true
  96812. });
  96813. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96814. /**
  96815. * Gets the inter-frames time capture status
  96816. */
  96817. get: function () {
  96818. return this._captureInterFrameTime;
  96819. },
  96820. /**
  96821. * Enable or disable the inter-frames time capture
  96822. */
  96823. set: function (value) {
  96824. this._captureInterFrameTime = value;
  96825. },
  96826. enumerable: true,
  96827. configurable: true
  96828. });
  96829. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96830. /**
  96831. * Gets the perf counter used for render time capture
  96832. */
  96833. get: function () {
  96834. return this._renderTime;
  96835. },
  96836. enumerable: true,
  96837. configurable: true
  96838. });
  96839. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96840. /**
  96841. * Gets the render time capture status
  96842. */
  96843. get: function () {
  96844. return this._captureRenderTime;
  96845. },
  96846. /**
  96847. * Enable or disable the render time capture
  96848. */
  96849. set: function (value) {
  96850. var _this = this;
  96851. if (value === this._captureRenderTime) {
  96852. return;
  96853. }
  96854. this._captureRenderTime = value;
  96855. if (value) {
  96856. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96857. _this._renderTime.beginMonitoring();
  96858. BABYLON.Tools.StartPerformanceCounter("Main render");
  96859. });
  96860. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96861. _this._renderTime.endMonitoring(false);
  96862. BABYLON.Tools.EndPerformanceCounter("Main render");
  96863. });
  96864. }
  96865. else {
  96866. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96867. this._onBeforeDrawPhaseObserver = null;
  96868. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96869. this._onAfterDrawPhaseObserver = null;
  96870. }
  96871. },
  96872. enumerable: true,
  96873. configurable: true
  96874. });
  96875. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96876. /**
  96877. * Gets the perf counter used for draw calls
  96878. */
  96879. get: function () {
  96880. return this.scene.getEngine()._drawCalls;
  96881. },
  96882. enumerable: true,
  96883. configurable: true
  96884. });
  96885. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96886. /**
  96887. * Gets the perf counter used for texture collisions
  96888. */
  96889. get: function () {
  96890. return this.scene.getEngine()._textureCollisions;
  96891. },
  96892. enumerable: true,
  96893. configurable: true
  96894. });
  96895. SceneInstrumentation.prototype.dispose = function () {
  96896. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96897. this._onAfterRenderObserver = null;
  96898. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96899. this._onBeforeActiveMeshesEvaluationObserver = null;
  96900. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96901. this._onAfterActiveMeshesEvaluationObserver = null;
  96902. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96903. this._onBeforeRenderTargetsRenderObserver = null;
  96904. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96905. this._onAfterRenderTargetsRenderObserver = null;
  96906. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96907. this._onBeforeAnimationsObserver = null;
  96908. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96909. this._onBeforeParticlesRenderingObserver = null;
  96910. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96911. this._onAfterParticlesRenderingObserver = null;
  96912. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96913. this._onBeforeSpritesRenderingObserver = null;
  96914. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96915. this._onAfterSpritesRenderingObserver = null;
  96916. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96917. this._onBeforeDrawPhaseObserver = null;
  96918. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96919. this._onAfterDrawPhaseObserver = null;
  96920. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96921. this._onBeforePhysicsObserver = null;
  96922. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96923. this._onAfterPhysicsObserver = null;
  96924. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96925. this._onAfterAnimationsObserver = null;
  96926. this.scene = null;
  96927. };
  96928. return SceneInstrumentation;
  96929. }());
  96930. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96931. })(BABYLON || (BABYLON = {}));
  96932. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96933. var BABYLON;
  96934. (function (BABYLON) {
  96935. /**
  96936. * @hidden
  96937. **/
  96938. var _TimeToken = /** @class */ (function () {
  96939. function _TimeToken() {
  96940. this._timeElapsedQueryEnded = false;
  96941. }
  96942. return _TimeToken;
  96943. }());
  96944. BABYLON._TimeToken = _TimeToken;
  96945. })(BABYLON || (BABYLON = {}));
  96946. //# sourceMappingURL=babylon.timeToken.js.map
  96947. var BABYLON;
  96948. (function (BABYLON) {
  96949. /**
  96950. * Background material defines definition.
  96951. * @hidden Mainly internal Use
  96952. */
  96953. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96954. __extends(BackgroundMaterialDefines, _super);
  96955. /**
  96956. * Constructor of the defines.
  96957. */
  96958. function BackgroundMaterialDefines() {
  96959. var _this = _super.call(this) || this;
  96960. /**
  96961. * True if the diffuse texture is in use.
  96962. */
  96963. _this.DIFFUSE = false;
  96964. /**
  96965. * The direct UV channel to use.
  96966. */
  96967. _this.DIFFUSEDIRECTUV = 0;
  96968. /**
  96969. * True if the diffuse texture is in gamma space.
  96970. */
  96971. _this.GAMMADIFFUSE = false;
  96972. /**
  96973. * True if the diffuse texture has opacity in the alpha channel.
  96974. */
  96975. _this.DIFFUSEHASALPHA = false;
  96976. /**
  96977. * True if you want the material to fade to transparent at grazing angle.
  96978. */
  96979. _this.OPACITYFRESNEL = false;
  96980. /**
  96981. * True if an extra blur needs to be added in the reflection.
  96982. */
  96983. _this.REFLECTIONBLUR = false;
  96984. /**
  96985. * True if you want the material to fade to reflection at grazing angle.
  96986. */
  96987. _this.REFLECTIONFRESNEL = false;
  96988. /**
  96989. * True if you want the material to falloff as far as you move away from the scene center.
  96990. */
  96991. _this.REFLECTIONFALLOFF = false;
  96992. /**
  96993. * False if the current Webgl implementation does not support the texture lod extension.
  96994. */
  96995. _this.TEXTURELODSUPPORT = false;
  96996. /**
  96997. * True to ensure the data are premultiplied.
  96998. */
  96999. _this.PREMULTIPLYALPHA = false;
  97000. /**
  97001. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  97002. */
  97003. _this.USERGBCOLOR = false;
  97004. /**
  97005. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  97006. * stays aligned with the desired configuration.
  97007. */
  97008. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  97009. /**
  97010. * True to add noise in order to reduce the banding effect.
  97011. */
  97012. _this.NOISE = false;
  97013. /**
  97014. * is the reflection texture in BGR color scheme?
  97015. * Mainly used to solve a bug in ios10 video tag
  97016. */
  97017. _this.REFLECTIONBGR = false;
  97018. _this.IMAGEPROCESSING = false;
  97019. _this.VIGNETTE = false;
  97020. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  97021. _this.VIGNETTEBLENDMODEOPAQUE = false;
  97022. _this.TONEMAPPING = false;
  97023. _this.CONTRAST = false;
  97024. _this.COLORCURVES = false;
  97025. _this.COLORGRADING = false;
  97026. _this.COLORGRADING3D = false;
  97027. _this.SAMPLER3DGREENDEPTH = false;
  97028. _this.SAMPLER3DBGRMAP = false;
  97029. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  97030. _this.EXPOSURE = false;
  97031. // Reflection.
  97032. _this.REFLECTION = false;
  97033. _this.REFLECTIONMAP_3D = false;
  97034. _this.REFLECTIONMAP_SPHERICAL = false;
  97035. _this.REFLECTIONMAP_PLANAR = false;
  97036. _this.REFLECTIONMAP_CUBIC = false;
  97037. _this.REFLECTIONMAP_PROJECTION = false;
  97038. _this.REFLECTIONMAP_SKYBOX = false;
  97039. _this.REFLECTIONMAP_EXPLICIT = false;
  97040. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97041. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97042. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97043. _this.INVERTCUBICMAP = false;
  97044. _this.REFLECTIONMAP_OPPOSITEZ = false;
  97045. _this.LODINREFLECTIONALPHA = false;
  97046. _this.GAMMAREFLECTION = false;
  97047. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  97048. // Default BJS.
  97049. _this.MAINUV1 = false;
  97050. _this.MAINUV2 = false;
  97051. _this.UV1 = false;
  97052. _this.UV2 = false;
  97053. _this.CLIPPLANE = false;
  97054. _this.POINTSIZE = false;
  97055. _this.FOG = false;
  97056. _this.NORMAL = false;
  97057. _this.NUM_BONE_INFLUENCERS = 0;
  97058. _this.BonesPerMesh = 0;
  97059. _this.INSTANCES = false;
  97060. _this.SHADOWFLOAT = false;
  97061. _this.rebuild();
  97062. return _this;
  97063. }
  97064. return BackgroundMaterialDefines;
  97065. }(BABYLON.MaterialDefines));
  97066. /**
  97067. * Background material used to create an efficient environement around your scene.
  97068. */
  97069. var BackgroundMaterial = /** @class */ (function (_super) {
  97070. __extends(BackgroundMaterial, _super);
  97071. /**
  97072. * Instantiates a Background Material in the given scene
  97073. * @param name The friendly name of the material
  97074. * @param scene The scene to add the material to
  97075. */
  97076. function BackgroundMaterial(name, scene) {
  97077. var _this = _super.call(this, name, scene) || this;
  97078. /**
  97079. * Key light Color (multiply against the environement texture)
  97080. */
  97081. _this.primaryColor = BABYLON.Color3.White();
  97082. _this._primaryColorShadowLevel = 0;
  97083. _this._primaryColorHighlightLevel = 0;
  97084. /**
  97085. * Reflection Texture used in the material.
  97086. * Should be author in a specific way for the best result (refer to the documentation).
  97087. */
  97088. _this.reflectionTexture = null;
  97089. /**
  97090. * Reflection Texture level of blur.
  97091. *
  97092. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  97093. * texture twice.
  97094. */
  97095. _this.reflectionBlur = 0;
  97096. /**
  97097. * Diffuse Texture used in the material.
  97098. * Should be author in a specific way for the best result (refer to the documentation).
  97099. */
  97100. _this.diffuseTexture = null;
  97101. _this._shadowLights = null;
  97102. /**
  97103. * Specify the list of lights casting shadow on the material.
  97104. * All scene shadow lights will be included if null.
  97105. */
  97106. _this.shadowLights = null;
  97107. /**
  97108. * Helps adjusting the shadow to a softer level if required.
  97109. * 0 means black shadows and 1 means no shadows.
  97110. */
  97111. _this.shadowLevel = 0;
  97112. /**
  97113. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  97114. * It is usually zero but might be interesting to modify according to your setup.
  97115. */
  97116. _this.sceneCenter = BABYLON.Vector3.Zero();
  97117. /**
  97118. * This helps specifying that the material is falling off to the sky box at grazing angle.
  97119. * This helps ensuring a nice transition when the camera goes under the ground.
  97120. */
  97121. _this.opacityFresnel = true;
  97122. /**
  97123. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  97124. * This helps adding a mirror texture on the ground.
  97125. */
  97126. _this.reflectionFresnel = false;
  97127. /**
  97128. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  97129. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  97130. */
  97131. _this.reflectionFalloffDistance = 0.0;
  97132. /**
  97133. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  97134. */
  97135. _this.reflectionAmount = 1.0;
  97136. /**
  97137. * This specifies the weight of the reflection at grazing angle.
  97138. */
  97139. _this.reflectionReflectance0 = 0.05;
  97140. /**
  97141. * This specifies the weight of the reflection at a perpendicular point of view.
  97142. */
  97143. _this.reflectionReflectance90 = 0.5;
  97144. /**
  97145. * Helps to directly use the maps channels instead of their level.
  97146. */
  97147. _this.useRGBColor = true;
  97148. /**
  97149. * This helps reducing the banding effect that could occur on the background.
  97150. */
  97151. _this.enableNoise = false;
  97152. _this._fovMultiplier = 1.0;
  97153. /**
  97154. * Enable the FOV adjustment feature controlled by fovMultiplier.
  97155. */
  97156. _this.useEquirectangularFOV = false;
  97157. _this._maxSimultaneousLights = 4;
  97158. /**
  97159. * Number of Simultaneous lights allowed on the material.
  97160. */
  97161. _this.maxSimultaneousLights = 4;
  97162. /**
  97163. * Keep track of the image processing observer to allow dispose and replace.
  97164. */
  97165. _this._imageProcessingObserver = null;
  97166. /**
  97167. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  97168. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  97169. */
  97170. _this.switchToBGR = false;
  97171. // Temp values kept as cache in the material.
  97172. _this._renderTargets = new BABYLON.SmartArray(16);
  97173. _this._reflectionControls = BABYLON.Vector4.Zero();
  97174. _this._white = BABYLON.Color3.White();
  97175. _this._primaryShadowColor = BABYLON.Color3.Black();
  97176. _this._primaryHighlightColor = BABYLON.Color3.Black();
  97177. // Setup the default processing configuration to the scene.
  97178. _this._attachImageProcessingConfiguration(null);
  97179. _this.getRenderTargetTextures = function () {
  97180. _this._renderTargets.reset();
  97181. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  97182. _this._renderTargets.push(_this._diffuseTexture);
  97183. }
  97184. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  97185. _this._renderTargets.push(_this._reflectionTexture);
  97186. }
  97187. return _this._renderTargets;
  97188. };
  97189. return _this;
  97190. }
  97191. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  97192. /**
  97193. * Experimental Internal Use Only.
  97194. *
  97195. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  97196. * This acts as a helper to set the primary color to a more "human friendly" value.
  97197. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  97198. * output color as close as possible from the chosen value.
  97199. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  97200. * part of lighting setup.)
  97201. */
  97202. get: function () {
  97203. return this.__perceptualColor;
  97204. },
  97205. set: function (value) {
  97206. this.__perceptualColor = value;
  97207. this._computePrimaryColorFromPerceptualColor();
  97208. this._markAllSubMeshesAsLightsDirty();
  97209. },
  97210. enumerable: true,
  97211. configurable: true
  97212. });
  97213. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  97214. /**
  97215. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  97216. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  97217. */
  97218. get: function () {
  97219. return this._primaryColorShadowLevel;
  97220. },
  97221. set: function (value) {
  97222. this._primaryColorShadowLevel = value;
  97223. this._computePrimaryColors();
  97224. this._markAllSubMeshesAsLightsDirty();
  97225. },
  97226. enumerable: true,
  97227. configurable: true
  97228. });
  97229. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  97230. /**
  97231. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  97232. * The primary color is used at the level chosen to define what the white area would look.
  97233. */
  97234. get: function () {
  97235. return this._primaryColorHighlightLevel;
  97236. },
  97237. set: function (value) {
  97238. this._primaryColorHighlightLevel = value;
  97239. this._computePrimaryColors();
  97240. this._markAllSubMeshesAsLightsDirty();
  97241. },
  97242. enumerable: true,
  97243. configurable: true
  97244. });
  97245. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  97246. /**
  97247. * Sets the reflection reflectance fresnel values according to the default standard
  97248. * empirically know to work well :-)
  97249. */
  97250. set: function (value) {
  97251. var reflectionWeight = value;
  97252. if (reflectionWeight < 0.5) {
  97253. reflectionWeight = reflectionWeight * 2.0;
  97254. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  97255. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  97256. }
  97257. else {
  97258. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  97259. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  97260. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  97261. }
  97262. },
  97263. enumerable: true,
  97264. configurable: true
  97265. });
  97266. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  97267. /**
  97268. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97269. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  97270. * Recommended to be keep at 1.0 except for special cases.
  97271. */
  97272. get: function () {
  97273. return this._fovMultiplier;
  97274. },
  97275. set: function (value) {
  97276. if (isNaN(value)) {
  97277. value = 1.0;
  97278. }
  97279. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  97280. },
  97281. enumerable: true,
  97282. configurable: true
  97283. });
  97284. /**
  97285. * Attaches a new image processing configuration to the PBR Material.
  97286. * @param configuration (if null the scene configuration will be use)
  97287. */
  97288. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  97289. var _this = this;
  97290. if (configuration === this._imageProcessingConfiguration) {
  97291. return;
  97292. }
  97293. // Detaches observer.
  97294. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97295. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97296. }
  97297. // Pick the scene configuration if needed.
  97298. if (!configuration) {
  97299. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  97300. }
  97301. else {
  97302. this._imageProcessingConfiguration = configuration;
  97303. }
  97304. // Attaches observer.
  97305. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  97306. _this._computePrimaryColorFromPerceptualColor();
  97307. _this._markAllSubMeshesAsImageProcessingDirty();
  97308. });
  97309. };
  97310. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  97311. /**
  97312. * Gets the image processing configuration used either in this material.
  97313. */
  97314. get: function () {
  97315. return this._imageProcessingConfiguration;
  97316. },
  97317. /**
  97318. * Sets the Default image processing configuration used either in the this material.
  97319. *
  97320. * If sets to null, the scene one is in use.
  97321. */
  97322. set: function (value) {
  97323. this._attachImageProcessingConfiguration(value);
  97324. // Ensure the effect will be rebuilt.
  97325. this._markAllSubMeshesAsTexturesDirty();
  97326. },
  97327. enumerable: true,
  97328. configurable: true
  97329. });
  97330. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  97331. /**
  97332. * Gets wether the color curves effect is enabled.
  97333. */
  97334. get: function () {
  97335. return this.imageProcessingConfiguration.colorCurvesEnabled;
  97336. },
  97337. /**
  97338. * Sets wether the color curves effect is enabled.
  97339. */
  97340. set: function (value) {
  97341. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  97342. },
  97343. enumerable: true,
  97344. configurable: true
  97345. });
  97346. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  97347. /**
  97348. * Gets wether the color grading effect is enabled.
  97349. */
  97350. get: function () {
  97351. return this.imageProcessingConfiguration.colorGradingEnabled;
  97352. },
  97353. /**
  97354. * Gets wether the color grading effect is enabled.
  97355. */
  97356. set: function (value) {
  97357. this.imageProcessingConfiguration.colorGradingEnabled = value;
  97358. },
  97359. enumerable: true,
  97360. configurable: true
  97361. });
  97362. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  97363. /**
  97364. * Gets wether tonemapping is enabled or not.
  97365. */
  97366. get: function () {
  97367. return this._imageProcessingConfiguration.toneMappingEnabled;
  97368. },
  97369. /**
  97370. * Sets wether tonemapping is enabled or not
  97371. */
  97372. set: function (value) {
  97373. this._imageProcessingConfiguration.toneMappingEnabled = value;
  97374. },
  97375. enumerable: true,
  97376. configurable: true
  97377. });
  97378. ;
  97379. ;
  97380. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  97381. /**
  97382. * The camera exposure used on this material.
  97383. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97384. * This corresponds to a photographic exposure.
  97385. */
  97386. get: function () {
  97387. return this._imageProcessingConfiguration.exposure;
  97388. },
  97389. /**
  97390. * The camera exposure used on this material.
  97391. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97392. * This corresponds to a photographic exposure.
  97393. */
  97394. set: function (value) {
  97395. this._imageProcessingConfiguration.exposure = value;
  97396. },
  97397. enumerable: true,
  97398. configurable: true
  97399. });
  97400. ;
  97401. ;
  97402. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  97403. /**
  97404. * Gets The camera contrast used on this material.
  97405. */
  97406. get: function () {
  97407. return this._imageProcessingConfiguration.contrast;
  97408. },
  97409. /**
  97410. * Sets The camera contrast used on this material.
  97411. */
  97412. set: function (value) {
  97413. this._imageProcessingConfiguration.contrast = value;
  97414. },
  97415. enumerable: true,
  97416. configurable: true
  97417. });
  97418. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  97419. /**
  97420. * Gets the Color Grading 2D Lookup Texture.
  97421. */
  97422. get: function () {
  97423. return this._imageProcessingConfiguration.colorGradingTexture;
  97424. },
  97425. /**
  97426. * Sets the Color Grading 2D Lookup Texture.
  97427. */
  97428. set: function (value) {
  97429. this.imageProcessingConfiguration.colorGradingTexture = value;
  97430. },
  97431. enumerable: true,
  97432. configurable: true
  97433. });
  97434. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  97435. /**
  97436. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97437. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97438. * 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;
  97439. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97440. */
  97441. get: function () {
  97442. return this.imageProcessingConfiguration.colorCurves;
  97443. },
  97444. /**
  97445. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97446. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97447. * 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;
  97448. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97449. */
  97450. set: function (value) {
  97451. this.imageProcessingConfiguration.colorCurves = value;
  97452. },
  97453. enumerable: true,
  97454. configurable: true
  97455. });
  97456. /**
  97457. * The entire material has been created in order to prevent overdraw.
  97458. * @returns false
  97459. */
  97460. BackgroundMaterial.prototype.needAlphaTesting = function () {
  97461. return true;
  97462. };
  97463. /**
  97464. * The entire material has been created in order to prevent overdraw.
  97465. * @returns true if blending is enable
  97466. */
  97467. BackgroundMaterial.prototype.needAlphaBlending = function () {
  97468. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  97469. };
  97470. /**
  97471. * Checks wether the material is ready to be rendered for a given mesh.
  97472. * @param mesh The mesh to render
  97473. * @param subMesh The submesh to check against
  97474. * @param useInstances Specify wether or not the material is used with instances
  97475. * @returns true if all the dependencies are ready (Textures, Effects...)
  97476. */
  97477. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  97478. var _this = this;
  97479. if (useInstances === void 0) { useInstances = false; }
  97480. if (subMesh.effect && this.isFrozen) {
  97481. if (this._wasPreviouslyReady) {
  97482. return true;
  97483. }
  97484. }
  97485. if (!subMesh._materialDefines) {
  97486. subMesh._materialDefines = new BackgroundMaterialDefines();
  97487. }
  97488. var scene = this.getScene();
  97489. var defines = subMesh._materialDefines;
  97490. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  97491. if (defines._renderId === scene.getRenderId()) {
  97492. return true;
  97493. }
  97494. }
  97495. var engine = scene.getEngine();
  97496. // Lights
  97497. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  97498. defines._needNormals = true;
  97499. // Textures
  97500. if (defines._areTexturesDirty) {
  97501. defines._needUVs = false;
  97502. if (scene.texturesEnabled) {
  97503. if (scene.getEngine().getCaps().textureLOD) {
  97504. defines.TEXTURELODSUPPORT = true;
  97505. }
  97506. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97507. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  97508. return false;
  97509. }
  97510. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  97511. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  97512. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  97513. defines.OPACITYFRESNEL = this._opacityFresnel;
  97514. }
  97515. else {
  97516. defines.DIFFUSE = false;
  97517. defines.DIFFUSEHASALPHA = false;
  97518. defines.GAMMADIFFUSE = false;
  97519. defines.OPACITYFRESNEL = false;
  97520. }
  97521. var reflectionTexture = this._reflectionTexture;
  97522. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97523. if (!reflectionTexture.isReadyOrNotBlocking()) {
  97524. return false;
  97525. }
  97526. defines.REFLECTION = true;
  97527. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  97528. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  97529. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  97530. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  97531. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  97532. defines.REFLECTIONBGR = this.switchToBGR;
  97533. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  97534. defines.INVERTCUBICMAP = true;
  97535. }
  97536. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  97537. switch (reflectionTexture.coordinatesMode) {
  97538. case BABYLON.Texture.EXPLICIT_MODE:
  97539. defines.REFLECTIONMAP_EXPLICIT = true;
  97540. break;
  97541. case BABYLON.Texture.PLANAR_MODE:
  97542. defines.REFLECTIONMAP_PLANAR = true;
  97543. break;
  97544. case BABYLON.Texture.PROJECTION_MODE:
  97545. defines.REFLECTIONMAP_PROJECTION = true;
  97546. break;
  97547. case BABYLON.Texture.SKYBOX_MODE:
  97548. defines.REFLECTIONMAP_SKYBOX = true;
  97549. break;
  97550. case BABYLON.Texture.SPHERICAL_MODE:
  97551. defines.REFLECTIONMAP_SPHERICAL = true;
  97552. break;
  97553. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97554. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97555. break;
  97556. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97557. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97558. break;
  97559. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97560. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97561. break;
  97562. case BABYLON.Texture.CUBIC_MODE:
  97563. case BABYLON.Texture.INVCUBIC_MODE:
  97564. default:
  97565. defines.REFLECTIONMAP_CUBIC = true;
  97566. break;
  97567. }
  97568. if (this.reflectionFresnel) {
  97569. defines.REFLECTIONFRESNEL = true;
  97570. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97571. this._reflectionControls.x = this.reflectionAmount;
  97572. this._reflectionControls.y = this.reflectionReflectance0;
  97573. this._reflectionControls.z = this.reflectionReflectance90;
  97574. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97575. }
  97576. else {
  97577. defines.REFLECTIONFRESNEL = false;
  97578. defines.REFLECTIONFALLOFF = false;
  97579. }
  97580. }
  97581. else {
  97582. defines.REFLECTION = false;
  97583. defines.REFLECTIONFRESNEL = false;
  97584. defines.REFLECTIONFALLOFF = false;
  97585. defines.REFLECTIONBLUR = false;
  97586. defines.REFLECTIONMAP_3D = false;
  97587. defines.REFLECTIONMAP_SPHERICAL = false;
  97588. defines.REFLECTIONMAP_PLANAR = false;
  97589. defines.REFLECTIONMAP_CUBIC = false;
  97590. defines.REFLECTIONMAP_PROJECTION = false;
  97591. defines.REFLECTIONMAP_SKYBOX = false;
  97592. defines.REFLECTIONMAP_EXPLICIT = false;
  97593. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97594. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97595. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97596. defines.INVERTCUBICMAP = false;
  97597. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97598. defines.LODINREFLECTIONALPHA = false;
  97599. defines.GAMMAREFLECTION = false;
  97600. }
  97601. }
  97602. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97603. defines.USERGBCOLOR = this._useRGBColor;
  97604. defines.NOISE = this._enableNoise;
  97605. }
  97606. if (defines._areLightsDirty) {
  97607. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97608. }
  97609. if (defines._areImageProcessingDirty) {
  97610. if (!this._imageProcessingConfiguration.isReady()) {
  97611. return false;
  97612. }
  97613. this._imageProcessingConfiguration.prepareDefines(defines);
  97614. }
  97615. // Misc.
  97616. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97617. // Values that need to be evaluated on every frame
  97618. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97619. // Attribs
  97620. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97621. if (mesh) {
  97622. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97623. mesh.createNormals(true);
  97624. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97625. }
  97626. }
  97627. }
  97628. // Get correct effect
  97629. if (defines.isDirty) {
  97630. defines.markAsProcessed();
  97631. scene.resetCachedMaterial();
  97632. // Fallbacks
  97633. var fallbacks = new BABYLON.EffectFallbacks();
  97634. if (defines.FOG) {
  97635. fallbacks.addFallback(0, "FOG");
  97636. }
  97637. if (defines.POINTSIZE) {
  97638. fallbacks.addFallback(1, "POINTSIZE");
  97639. }
  97640. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97641. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97642. fallbacks.addCPUSkinningFallback(0, mesh);
  97643. }
  97644. //Attributes
  97645. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97646. if (defines.NORMAL) {
  97647. attribs.push(BABYLON.VertexBuffer.NormalKind);
  97648. }
  97649. if (defines.UV1) {
  97650. attribs.push(BABYLON.VertexBuffer.UVKind);
  97651. }
  97652. if (defines.UV2) {
  97653. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97654. }
  97655. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  97656. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  97657. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  97658. "vFogInfos", "vFogColor", "pointSize",
  97659. "vClipPlane", "mBones",
  97660. "vPrimaryColor", "vPrimaryColorShadow",
  97661. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  97662. "shadowLevel", "alpha",
  97663. "vBackgroundCenter", "vReflectionControl",
  97664. "vDiffuseInfos", "diffuseMatrix",
  97665. ];
  97666. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  97667. var uniformBuffers = ["Material", "Scene"];
  97668. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  97669. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  97670. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  97671. uniformsNames: uniforms,
  97672. uniformBuffersNames: uniformBuffers,
  97673. samplers: samplers,
  97674. defines: defines,
  97675. maxSimultaneousLights: this._maxSimultaneousLights
  97676. });
  97677. var onCompiled = function (effect) {
  97678. if (_this.onCompiled) {
  97679. _this.onCompiled(effect);
  97680. }
  97681. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  97682. };
  97683. var join = defines.toString();
  97684. subMesh.setEffect(scene.getEngine().createEffect("background", {
  97685. attributes: attribs,
  97686. uniformsNames: uniforms,
  97687. uniformBuffersNames: uniformBuffers,
  97688. samplers: samplers,
  97689. defines: join,
  97690. fallbacks: fallbacks,
  97691. onCompiled: onCompiled,
  97692. onError: this.onError,
  97693. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  97694. }, engine), defines);
  97695. this.buildUniformLayout();
  97696. }
  97697. if (!subMesh.effect || !subMesh.effect.isReady()) {
  97698. return false;
  97699. }
  97700. defines._renderId = scene.getRenderId();
  97701. this._wasPreviouslyReady = true;
  97702. return true;
  97703. };
  97704. /**
  97705. * Compute the primary color according to the chosen perceptual color.
  97706. */
  97707. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  97708. if (!this.__perceptualColor) {
  97709. return;
  97710. }
  97711. this._primaryColor.copyFrom(this.__perceptualColor);
  97712. // Revert gamma space.
  97713. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  97714. // Revert image processing configuration.
  97715. if (this._imageProcessingConfiguration) {
  97716. // Revert Exposure.
  97717. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97718. }
  97719. this._computePrimaryColors();
  97720. };
  97721. /**
  97722. * Compute the highlights and shadow colors according to their chosen levels.
  97723. */
  97724. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97725. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97726. return;
  97727. }
  97728. // Find the highlight color based on the configuration.
  97729. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97730. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97731. // Find the shadow color based on the configuration.
  97732. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97733. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97734. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97735. };
  97736. /**
  97737. * Build the uniform buffer used in the material.
  97738. */
  97739. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97740. // Order is important !
  97741. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97742. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97743. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97744. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97745. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97746. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97747. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97748. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97749. this._uniformBuffer.addUniform("pointSize", 1);
  97750. this._uniformBuffer.addUniform("shadowLevel", 1);
  97751. this._uniformBuffer.addUniform("alpha", 1);
  97752. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97753. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97754. this._uniformBuffer.create();
  97755. };
  97756. /**
  97757. * Unbind the material.
  97758. */
  97759. BackgroundMaterial.prototype.unbind = function () {
  97760. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97761. this._uniformBuffer.setTexture("diffuseSampler", null);
  97762. }
  97763. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97764. this._uniformBuffer.setTexture("reflectionSampler", null);
  97765. }
  97766. _super.prototype.unbind.call(this);
  97767. };
  97768. /**
  97769. * Bind only the world matrix to the material.
  97770. * @param world The world matrix to bind.
  97771. */
  97772. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97773. this._activeEffect.setMatrix("world", world);
  97774. };
  97775. /**
  97776. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97777. * @param world The world matrix to bind.
  97778. * @param subMesh The submesh to bind for.
  97779. */
  97780. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97781. var scene = this.getScene();
  97782. var defines = subMesh._materialDefines;
  97783. if (!defines) {
  97784. return;
  97785. }
  97786. var effect = subMesh.effect;
  97787. if (!effect) {
  97788. return;
  97789. }
  97790. this._activeEffect = effect;
  97791. // Matrices
  97792. this.bindOnlyWorldMatrix(world);
  97793. // Bones
  97794. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97795. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97796. if (mustRebind) {
  97797. this._uniformBuffer.bindToEffect(effect, "Material");
  97798. this.bindViewProjection(effect);
  97799. var reflectionTexture = this._reflectionTexture;
  97800. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97801. // Texture uniforms
  97802. if (scene.texturesEnabled) {
  97803. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97804. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97805. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97806. }
  97807. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97808. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97809. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97810. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97811. }
  97812. }
  97813. if (this.shadowLevel > 0) {
  97814. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97815. }
  97816. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97817. // Point size
  97818. if (this.pointsCloud) {
  97819. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97820. }
  97821. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97822. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97823. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97824. }
  97825. else {
  97826. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97827. }
  97828. }
  97829. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97830. // Textures
  97831. if (scene.texturesEnabled) {
  97832. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97833. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97834. }
  97835. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97836. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97837. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97838. }
  97839. else if (!defines.REFLECTIONBLUR) {
  97840. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97841. }
  97842. else {
  97843. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97844. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97845. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97846. }
  97847. if (defines.REFLECTIONFRESNEL) {
  97848. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97849. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97850. }
  97851. }
  97852. }
  97853. // Clip plane
  97854. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97855. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97856. }
  97857. if (mustRebind || !this.isFrozen) {
  97858. if (scene.lightsEnabled) {
  97859. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97860. }
  97861. // View
  97862. this.bindView(effect);
  97863. // Fog
  97864. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97865. // image processing
  97866. this._imageProcessingConfiguration.bind(this._activeEffect);
  97867. }
  97868. this._uniformBuffer.update();
  97869. this._afterBind(mesh);
  97870. };
  97871. /**
  97872. * Dispose the material.
  97873. * @param forceDisposeEffect Force disposal of the associated effect.
  97874. * @param forceDisposeTextures Force disposal of the associated textures.
  97875. */
  97876. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97877. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97878. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97879. if (forceDisposeTextures) {
  97880. if (this.diffuseTexture) {
  97881. this.diffuseTexture.dispose();
  97882. }
  97883. if (this.reflectionTexture) {
  97884. this.reflectionTexture.dispose();
  97885. }
  97886. }
  97887. this._renderTargets.dispose();
  97888. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97889. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97890. }
  97891. _super.prototype.dispose.call(this, forceDisposeEffect);
  97892. };
  97893. /**
  97894. * Clones the material.
  97895. * @param name The cloned name.
  97896. * @returns The cloned material.
  97897. */
  97898. BackgroundMaterial.prototype.clone = function (name) {
  97899. var _this = this;
  97900. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97901. };
  97902. /**
  97903. * Serializes the current material to its JSON representation.
  97904. * @returns The JSON representation.
  97905. */
  97906. BackgroundMaterial.prototype.serialize = function () {
  97907. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97908. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97909. return serializationObject;
  97910. };
  97911. /**
  97912. * Gets the class name of the material
  97913. * @returns "BackgroundMaterial"
  97914. */
  97915. BackgroundMaterial.prototype.getClassName = function () {
  97916. return "BackgroundMaterial";
  97917. };
  97918. /**
  97919. * Parse a JSON input to create back a background material.
  97920. * @param source The JSON data to parse
  97921. * @param scene The scene to create the parsed material in
  97922. * @param rootUrl The root url of the assets the material depends upon
  97923. * @returns the instantiated BackgroundMaterial.
  97924. */
  97925. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97926. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97927. };
  97928. /**
  97929. * Standard reflectance value at parallel view angle.
  97930. */
  97931. BackgroundMaterial.StandardReflectance0 = 0.05;
  97932. /**
  97933. * Standard reflectance value at grazing angle.
  97934. */
  97935. BackgroundMaterial.StandardReflectance90 = 0.5;
  97936. __decorate([
  97937. BABYLON.serializeAsColor3()
  97938. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97939. __decorate([
  97940. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97941. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97942. __decorate([
  97943. BABYLON.serializeAsColor3()
  97944. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97945. __decorate([
  97946. BABYLON.serialize()
  97947. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97948. __decorate([
  97949. BABYLON.serialize()
  97950. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97951. __decorate([
  97952. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97953. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97954. __decorate([
  97955. BABYLON.serializeAsTexture()
  97956. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97957. __decorate([
  97958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97959. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97960. __decorate([
  97961. BABYLON.serialize()
  97962. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97963. __decorate([
  97964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97965. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97966. __decorate([
  97967. BABYLON.serializeAsTexture()
  97968. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97969. __decorate([
  97970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97971. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97972. __decorate([
  97973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97974. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97975. __decorate([
  97976. BABYLON.serialize()
  97977. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97978. __decorate([
  97979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97980. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97981. __decorate([
  97982. BABYLON.serializeAsVector3()
  97983. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97984. __decorate([
  97985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97986. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97987. __decorate([
  97988. BABYLON.serialize()
  97989. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97990. __decorate([
  97991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97992. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97993. __decorate([
  97994. BABYLON.serialize()
  97995. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97996. __decorate([
  97997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97998. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97999. __decorate([
  98000. BABYLON.serialize()
  98001. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  98002. __decorate([
  98003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98004. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  98005. __decorate([
  98006. BABYLON.serialize()
  98007. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  98008. __decorate([
  98009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98010. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  98011. __decorate([
  98012. BABYLON.serialize()
  98013. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  98014. __decorate([
  98015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98016. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  98017. __decorate([
  98018. BABYLON.serialize()
  98019. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  98020. __decorate([
  98021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98022. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  98023. __decorate([
  98024. BABYLON.serialize()
  98025. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  98026. __decorate([
  98027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98028. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  98029. __decorate([
  98030. BABYLON.serialize()
  98031. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  98032. __decorate([
  98033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98034. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  98035. __decorate([
  98036. BABYLON.serialize()
  98037. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  98038. __decorate([
  98039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98040. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  98041. __decorate([
  98042. BABYLON.serializeAsImageProcessingConfiguration()
  98043. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  98044. return BackgroundMaterial;
  98045. }(BABYLON.PushMaterial));
  98046. BABYLON.BackgroundMaterial = BackgroundMaterial;
  98047. })(BABYLON || (BABYLON = {}));
  98048. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  98049. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98050. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98051. s = arguments[i];
  98052. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98053. t[p] = s[p];
  98054. }
  98055. return t;
  98056. };
  98057. var BABYLON;
  98058. (function (BABYLON) {
  98059. /**
  98060. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  98061. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  98062. * It also helps with the default setup of your imageProcessing configuration.
  98063. */
  98064. var EnvironmentHelper = /** @class */ (function () {
  98065. /**
  98066. * constructor
  98067. * @param options
  98068. * @param scene The scene to add the material to
  98069. */
  98070. function EnvironmentHelper(options, scene) {
  98071. var _this = this;
  98072. this._errorHandler = function (message, exception) {
  98073. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  98074. };
  98075. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  98076. this._scene = scene;
  98077. this.onErrorObservable = new BABYLON.Observable();
  98078. this._setupBackground();
  98079. this._setupImageProcessing();
  98080. }
  98081. /**
  98082. * Creates the default options for the helper.
  98083. */
  98084. EnvironmentHelper._getDefaultOptions = function () {
  98085. return {
  98086. createGround: true,
  98087. groundSize: 15,
  98088. groundTexture: this._groundTextureCDNUrl,
  98089. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98090. groundOpacity: 0.9,
  98091. enableGroundShadow: true,
  98092. groundShadowLevel: 0.5,
  98093. enableGroundMirror: false,
  98094. groundMirrorSizeRatio: 0.3,
  98095. groundMirrorBlurKernel: 64,
  98096. groundMirrorAmount: 1,
  98097. groundMirrorFresnelWeight: 1,
  98098. groundMirrorFallOffDistance: 0,
  98099. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  98100. groundYBias: 0.00001,
  98101. createSkybox: true,
  98102. skyboxSize: 20,
  98103. skyboxTexture: this._skyboxTextureCDNUrl,
  98104. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98105. backgroundYRotation: 0,
  98106. sizeAuto: true,
  98107. rootPosition: BABYLON.Vector3.Zero(),
  98108. setupImageProcessing: true,
  98109. environmentTexture: this._environmentTextureCDNUrl,
  98110. cameraExposure: 0.8,
  98111. cameraContrast: 1.2,
  98112. toneMappingEnabled: true,
  98113. };
  98114. };
  98115. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  98116. /**
  98117. * Gets the root mesh created by the helper.
  98118. */
  98119. get: function () {
  98120. return this._rootMesh;
  98121. },
  98122. enumerable: true,
  98123. configurable: true
  98124. });
  98125. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  98126. /**
  98127. * Gets the skybox created by the helper.
  98128. */
  98129. get: function () {
  98130. return this._skybox;
  98131. },
  98132. enumerable: true,
  98133. configurable: true
  98134. });
  98135. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  98136. /**
  98137. * Gets the skybox texture created by the helper.
  98138. */
  98139. get: function () {
  98140. return this._skyboxTexture;
  98141. },
  98142. enumerable: true,
  98143. configurable: true
  98144. });
  98145. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  98146. /**
  98147. * Gets the skybox material created by the helper.
  98148. */
  98149. get: function () {
  98150. return this._skyboxMaterial;
  98151. },
  98152. enumerable: true,
  98153. configurable: true
  98154. });
  98155. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  98156. /**
  98157. * Gets the ground mesh created by the helper.
  98158. */
  98159. get: function () {
  98160. return this._ground;
  98161. },
  98162. enumerable: true,
  98163. configurable: true
  98164. });
  98165. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  98166. /**
  98167. * Gets the ground texture created by the helper.
  98168. */
  98169. get: function () {
  98170. return this._groundTexture;
  98171. },
  98172. enumerable: true,
  98173. configurable: true
  98174. });
  98175. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  98176. /**
  98177. * Gets the ground mirror created by the helper.
  98178. */
  98179. get: function () {
  98180. return this._groundMirror;
  98181. },
  98182. enumerable: true,
  98183. configurable: true
  98184. });
  98185. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  98186. /**
  98187. * Gets the ground mirror render list to helps pushing the meshes
  98188. * you wish in the ground reflection.
  98189. */
  98190. get: function () {
  98191. if (this._groundMirror) {
  98192. return this._groundMirror.renderList;
  98193. }
  98194. return null;
  98195. },
  98196. enumerable: true,
  98197. configurable: true
  98198. });
  98199. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  98200. /**
  98201. * Gets the ground material created by the helper.
  98202. */
  98203. get: function () {
  98204. return this._groundMaterial;
  98205. },
  98206. enumerable: true,
  98207. configurable: true
  98208. });
  98209. /**
  98210. * Updates the background according to the new options
  98211. * @param options
  98212. */
  98213. EnvironmentHelper.prototype.updateOptions = function (options) {
  98214. var newOptions = __assign({}, this._options, options);
  98215. if (this._ground && !newOptions.createGround) {
  98216. this._ground.dispose();
  98217. this._ground = null;
  98218. }
  98219. if (this._groundMaterial && !newOptions.createGround) {
  98220. this._groundMaterial.dispose();
  98221. this._groundMaterial = null;
  98222. }
  98223. if (this._groundTexture) {
  98224. if (this._options.groundTexture != newOptions.groundTexture) {
  98225. this._groundTexture.dispose();
  98226. this._groundTexture = null;
  98227. }
  98228. }
  98229. if (this._skybox && !newOptions.createSkybox) {
  98230. this._skybox.dispose();
  98231. this._skybox = null;
  98232. }
  98233. if (this._skyboxMaterial && !newOptions.createSkybox) {
  98234. this._skyboxMaterial.dispose();
  98235. this._skyboxMaterial = null;
  98236. }
  98237. if (this._skyboxTexture) {
  98238. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  98239. this._skyboxTexture.dispose();
  98240. this._skyboxTexture = null;
  98241. }
  98242. }
  98243. if (this._groundMirror && !newOptions.enableGroundMirror) {
  98244. this._groundMirror.dispose();
  98245. this._groundMirror = null;
  98246. }
  98247. if (this._scene.environmentTexture) {
  98248. if (this._options.environmentTexture != newOptions.environmentTexture) {
  98249. this._scene.environmentTexture.dispose();
  98250. }
  98251. }
  98252. this._options = newOptions;
  98253. this._setupBackground();
  98254. this._setupImageProcessing();
  98255. };
  98256. /**
  98257. * Sets the primary color of all the available elements.
  98258. * @param color the main color to affect to the ground and the background
  98259. */
  98260. EnvironmentHelper.prototype.setMainColor = function (color) {
  98261. if (this.groundMaterial) {
  98262. this.groundMaterial.primaryColor = color;
  98263. }
  98264. if (this.skyboxMaterial) {
  98265. this.skyboxMaterial.primaryColor = color;
  98266. }
  98267. if (this.groundMirror) {
  98268. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  98269. }
  98270. };
  98271. /**
  98272. * Setup the image processing according to the specified options.
  98273. */
  98274. EnvironmentHelper.prototype._setupImageProcessing = function () {
  98275. if (this._options.setupImageProcessing) {
  98276. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  98277. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  98278. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  98279. this._setupEnvironmentTexture();
  98280. }
  98281. };
  98282. /**
  98283. * Setup the environment texture according to the specified options.
  98284. */
  98285. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  98286. if (this._scene.environmentTexture) {
  98287. return;
  98288. }
  98289. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  98290. this._scene.environmentTexture = this._options.environmentTexture;
  98291. return;
  98292. }
  98293. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  98294. this._scene.environmentTexture = environmentTexture;
  98295. };
  98296. /**
  98297. * Setup the background according to the specified options.
  98298. */
  98299. EnvironmentHelper.prototype._setupBackground = function () {
  98300. if (!this._rootMesh) {
  98301. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  98302. }
  98303. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  98304. var sceneSize = this._getSceneSize();
  98305. if (this._options.createGround) {
  98306. this._setupGround(sceneSize);
  98307. this._setupGroundMaterial();
  98308. this._setupGroundDiffuseTexture();
  98309. if (this._options.enableGroundMirror) {
  98310. this._setupGroundMirrorTexture(sceneSize);
  98311. }
  98312. this._setupMirrorInGroundMaterial();
  98313. }
  98314. if (this._options.createSkybox) {
  98315. this._setupSkybox(sceneSize);
  98316. this._setupSkyboxMaterial();
  98317. this._setupSkyboxReflectionTexture();
  98318. }
  98319. this._rootMesh.position.x = sceneSize.rootPosition.x;
  98320. this._rootMesh.position.z = sceneSize.rootPosition.z;
  98321. this._rootMesh.position.y = sceneSize.rootPosition.y;
  98322. };
  98323. /**
  98324. * Get the scene sizes according to the setup.
  98325. */
  98326. EnvironmentHelper.prototype._getSceneSize = function () {
  98327. var _this = this;
  98328. var groundSize = this._options.groundSize;
  98329. var skyboxSize = this._options.skyboxSize;
  98330. var rootPosition = this._options.rootPosition;
  98331. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  98332. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98333. }
  98334. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  98335. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  98336. });
  98337. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98338. if (this._options.sizeAuto) {
  98339. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  98340. this._scene.activeCamera.upperRadiusLimit) {
  98341. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  98342. skyboxSize = groundSize;
  98343. }
  98344. var sceneDiagonalLenght = sceneDiagonal.length();
  98345. if (sceneDiagonalLenght > groundSize) {
  98346. groundSize = sceneDiagonalLenght * 2;
  98347. skyboxSize = groundSize;
  98348. }
  98349. // 10 % bigger.
  98350. groundSize *= 1.1;
  98351. skyboxSize *= 1.5;
  98352. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  98353. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  98354. }
  98355. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98356. };
  98357. /**
  98358. * Setup the ground according to the specified options.
  98359. */
  98360. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  98361. var _this = this;
  98362. if (!this._ground) {
  98363. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  98364. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  98365. this._ground.parent = this._rootMesh;
  98366. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  98367. }
  98368. this._ground.receiveShadows = this._options.enableGroundShadow;
  98369. };
  98370. /**
  98371. * Setup the ground material according to the specified options.
  98372. */
  98373. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  98374. if (!this._groundMaterial) {
  98375. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  98376. }
  98377. this._groundMaterial.alpha = this._options.groundOpacity;
  98378. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  98379. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  98380. this._groundMaterial.primaryColor = this._options.groundColor;
  98381. this._groundMaterial.useRGBColor = false;
  98382. this._groundMaterial.enableNoise = true;
  98383. if (this._ground) {
  98384. this._ground.material = this._groundMaterial;
  98385. }
  98386. };
  98387. /**
  98388. * Setup the ground diffuse texture according to the specified options.
  98389. */
  98390. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  98391. if (!this._groundMaterial) {
  98392. return;
  98393. }
  98394. if (this._groundTexture) {
  98395. return;
  98396. }
  98397. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  98398. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  98399. return;
  98400. }
  98401. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98402. diffuseTexture.gammaSpace = false;
  98403. diffuseTexture.hasAlpha = true;
  98404. this._groundMaterial.diffuseTexture = diffuseTexture;
  98405. };
  98406. /**
  98407. * Setup the ground mirror texture according to the specified options.
  98408. */
  98409. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  98410. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98411. if (!this._groundMirror) {
  98412. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  98413. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  98414. this._groundMirror.anisotropicFilteringLevel = 1;
  98415. this._groundMirror.wrapU = wrapping;
  98416. this._groundMirror.wrapV = wrapping;
  98417. this._groundMirror.gammaSpace = false;
  98418. if (this._groundMirror.renderList) {
  98419. for (var i = 0; i < this._scene.meshes.length; i++) {
  98420. var mesh = this._scene.meshes[i];
  98421. if (mesh !== this._ground &&
  98422. mesh !== this._skybox &&
  98423. mesh !== this._rootMesh) {
  98424. this._groundMirror.renderList.push(mesh);
  98425. }
  98426. }
  98427. }
  98428. }
  98429. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  98430. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  98431. };
  98432. /**
  98433. * Setup the ground to receive the mirror texture.
  98434. */
  98435. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  98436. if (this._groundMaterial) {
  98437. this._groundMaterial.reflectionTexture = this._groundMirror;
  98438. this._groundMaterial.reflectionFresnel = true;
  98439. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  98440. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  98441. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  98442. }
  98443. };
  98444. /**
  98445. * Setup the skybox according to the specified options.
  98446. */
  98447. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  98448. var _this = this;
  98449. if (!this._skybox) {
  98450. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  98451. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  98452. }
  98453. this._skybox.parent = this._rootMesh;
  98454. };
  98455. /**
  98456. * Setup the skybox material according to the specified options.
  98457. */
  98458. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  98459. if (!this._skybox) {
  98460. return;
  98461. }
  98462. if (!this._skyboxMaterial) {
  98463. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  98464. }
  98465. this._skyboxMaterial.useRGBColor = false;
  98466. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  98467. this._skyboxMaterial.enableNoise = true;
  98468. this._skybox.material = this._skyboxMaterial;
  98469. };
  98470. /**
  98471. * Setup the skybox reflection texture according to the specified options.
  98472. */
  98473. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  98474. if (!this._skyboxMaterial) {
  98475. return;
  98476. }
  98477. if (this._skyboxTexture) {
  98478. return;
  98479. }
  98480. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  98481. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  98482. return;
  98483. }
  98484. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98485. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  98486. this._skyboxTexture.gammaSpace = false;
  98487. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  98488. };
  98489. /**
  98490. * Dispose all the elements created by the Helper.
  98491. */
  98492. EnvironmentHelper.prototype.dispose = function () {
  98493. if (this._groundMaterial) {
  98494. this._groundMaterial.dispose(true, true);
  98495. }
  98496. if (this._skyboxMaterial) {
  98497. this._skyboxMaterial.dispose(true, true);
  98498. }
  98499. this._rootMesh.dispose(false);
  98500. };
  98501. /**
  98502. * Default ground texture URL.
  98503. */
  98504. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  98505. /**
  98506. * Default skybox texture URL.
  98507. */
  98508. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  98509. /**
  98510. * Default environment texture URL.
  98511. */
  98512. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  98513. return EnvironmentHelper;
  98514. }());
  98515. BABYLON.EnvironmentHelper = EnvironmentHelper;
  98516. })(BABYLON || (BABYLON = {}));
  98517. //# sourceMappingURL=babylon.environmentHelper.js.map
  98518. var BABYLON;
  98519. (function (BABYLON) {
  98520. /**
  98521. * This class is made for on one-liner static method to help creating particle systems.
  98522. */
  98523. var ParticleHelper = /** @class */ (function () {
  98524. function ParticleHelper() {
  98525. }
  98526. /**
  98527. * This is the main static method (one-liner) of this helper to create different particle systems.
  98528. * @param type This string represents the type to the particle system to create
  98529. * @param emitter The object where the particle system will start to emit from.
  98530. * @param scene The scene where the particle system should live.
  98531. * @param gpu If the system will use gpu.
  98532. * @returns the ParticleSystem created.
  98533. */
  98534. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  98535. var _this = this;
  98536. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  98537. if (gpu === void 0) { gpu = false; }
  98538. return new Promise(function (resolve, reject) {
  98539. if (scene) {
  98540. _this._scene = scene;
  98541. }
  98542. else {
  98543. return reject("A particle system need a scene.");
  98544. }
  98545. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  98546. return reject("Particle system with GPU is not supported.");
  98547. }
  98548. _this._emitter = emitter;
  98549. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  98550. var newData = JSON.parse(data.toString());
  98551. return resolve(_this._createSystem(newData));
  98552. }, undefined, undefined, undefined, function (req, exception) {
  98553. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98554. });
  98555. });
  98556. };
  98557. ParticleHelper._createSystem = function (data) {
  98558. // Create a particle system
  98559. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98560. // Texture of each particle
  98561. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98562. // Where the particles come from
  98563. system.emitter = this._emitter; // the starting object, the emitter
  98564. // Colors of all particles
  98565. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98566. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98567. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98568. // Size of each particle (random between...
  98569. system.minSize = data.minSize;
  98570. system.maxSize = data.maxSize;
  98571. // Life time of each particle (random between...
  98572. system.minLifeTime = data.minLifeTime;
  98573. system.maxLifeTime = data.maxLifeTime;
  98574. // Emission rate
  98575. system.emitRate = data.emitRate;
  98576. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98577. system.blendMode = data.blendMode;
  98578. // Set the gravity of all particles
  98579. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98580. // Angular speed, in radians
  98581. system.minAngularSpeed = data.minAngularSpeed;
  98582. system.maxAngularSpeed = data.maxAngularSpeed;
  98583. // Speed
  98584. system.minEmitPower = data.minEmitPower;
  98585. system.maxEmitPower = data.maxEmitPower;
  98586. system.updateSpeed = data.updateSpeed;
  98587. switch (data.emitterType) {
  98588. case "box":
  98589. if (!data.direction1 || !data.direction2) {
  98590. throw new Error("Directions are missing in this particle system.");
  98591. }
  98592. if (!data.minEmitBox || !data.maxEmitBox) {
  98593. throw new Error("EmitBox is missing in this particle system.");
  98594. }
  98595. 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));
  98596. break;
  98597. case "sphere":
  98598. system.createSphereEmitter(data.radius);
  98599. break;
  98600. case "directed_sphere":
  98601. if (!data.direction1 || !data.direction2) {
  98602. throw new Error("Directions are missing in this particle system.");
  98603. }
  98604. 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));
  98605. break;
  98606. case "cone":
  98607. system.createConeEmitter(data.radius, data.angle);
  98608. break;
  98609. default:
  98610. break;
  98611. }
  98612. return system;
  98613. };
  98614. /**
  98615. * Base Assets URL.
  98616. */
  98617. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98618. return ParticleHelper;
  98619. }());
  98620. BABYLON.ParticleHelper = ParticleHelper;
  98621. })(BABYLON || (BABYLON = {}));
  98622. //# sourceMappingURL=babylon.particleHelper.js.map
  98623. var BABYLON;
  98624. (function (BABYLON) {
  98625. /**
  98626. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98627. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98628. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98629. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98630. */
  98631. var VideoDome = /** @class */ (function (_super) {
  98632. __extends(VideoDome, _super);
  98633. /**
  98634. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98635. * @param name Element's name, child elements will append suffixes for their own names.
  98636. * @param urlsOrVideo
  98637. * @param options An object containing optional or exposed sub element properties:
  98638. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98639. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98640. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98641. * @param options **loop=true** Automatically loop video on end.
  98642. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98643. */
  98644. function VideoDome(name, urlsOrVideo, options, scene) {
  98645. var _this = _super.call(this, name, scene) || this;
  98646. // set defaults and manage values
  98647. name = name || "videoDome";
  98648. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  98649. options.clickToPlay = Boolean(options.clickToPlay);
  98650. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  98651. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  98652. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  98653. // create
  98654. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  98655. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  98656. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  98657. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  98658. flat: false,
  98659. radius: options.size,
  98660. subdivisions: options.resolution,
  98661. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  98662. }, scene);
  98663. // configure material
  98664. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  98665. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  98666. material.reflectionTexture = _this._videoTexture;
  98667. material.useEquirectangularFOV = true;
  98668. material.fovMultiplier = 1.0;
  98669. // configure mesh
  98670. _this._mesh.material = material;
  98671. _this._mesh.parent = _this;
  98672. // optional configuration
  98673. if (options.clickToPlay) {
  98674. scene.onPointerUp = function () {
  98675. _this._videoTexture.video.play();
  98676. };
  98677. }
  98678. return _this;
  98679. }
  98680. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  98681. /**
  98682. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98683. * Also see the options.resolution property.
  98684. */
  98685. get: function () {
  98686. return this._material.fovMultiplier;
  98687. },
  98688. set: function (value) {
  98689. this._material.fovMultiplier = value;
  98690. },
  98691. enumerable: true,
  98692. configurable: true
  98693. });
  98694. /**
  98695. * Releases resources associated with this node.
  98696. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  98697. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  98698. */
  98699. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  98700. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  98701. this._videoTexture.dispose();
  98702. this._mesh.dispose();
  98703. this._material.dispose();
  98704. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  98705. };
  98706. return VideoDome;
  98707. }(BABYLON.Node));
  98708. BABYLON.VideoDome = VideoDome;
  98709. })(BABYLON || (BABYLON = {}));
  98710. //# sourceMappingURL=babylon.videoDome.js.map
  98711. 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"};
  98712. 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};"};
  98713. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  98714. globalObject["BABYLON"] = BABYLON;
  98715. //backwards compatibility
  98716. if(typeof earcut !== 'undefined') {
  98717. globalObject["Earcut"] = {
  98718. earcut: earcut
  98719. };
  98720. }
  98721. return BABYLON;
  98722. });